repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
matscipy
matscipy-master/matscipy/calculators/eam/calculator.py
# # Copyright 2019-2020 Wolfram G. Nöhring (U. Freiburg) # 2015, 2019 Lars Pastewka (U. Freiburg) # 2015 Adrien Gola (KIT) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """EAM calculator""" import numpy as np from ase.calculators.calculator import Calculator from matscipy.calculators.calculator import MatscipyCalculator try: from scipy.interpolate import InterpolatedUnivariateSpline except ImportError: InterpolatedUnivariateSpline = None from scipy.sparse import bsr_matrix from matscipy.calculators.eam.io import read_eam from matscipy.neighbours import ( neighbour_list, first_neighbours, find_indices_of_reversed_pairs, find_common_neighbours ) ### def _make_splines(dx, y): if len(np.asarray(y).shape) > 1: return [_make_splines(dx, yy) for yy in y] else: return InterpolatedUnivariateSpline(np.arange(len(y))*dx, y) def _make_derivative(x, n=1): if type(x) == list: return [_make_derivative(xx, n=n) for xx in x] else: return x.derivative(n=n) ### class EAM(MatscipyCalculator): implemented_properties = ['energy', 'free_energy', 'stress', 'forces', 'hessian'] default_parameters = {} name = 'EAM' def __init__(self, fn=None, atomic_numbers=None, F=None, f=None, rep=None, cutoff=None, kind='eam/alloy'): super().__init__() if fn is not None: source, parameters, F, f, rep = read_eam(fn, kind=kind) self._db_atomic_numbers = parameters.atomic_numbers self._db_cutoff = parameters.cutoff dr = parameters.distance_grid_spacing dF = parameters.density_grid_spacing # Create spline interpolation self.F = _make_splines(dF, F) self.f = _make_splines(dr, f) self.rep = _make_splines(dr, rep) else: self._db_atomic_numbers = atomic_numbers self.F = F self.f = f self.rep = rep self._db_cutoff = cutoff self.atnum_to_index = -np.ones(np.max(self._db_atomic_numbers)+1, dtype=int) self.atnum_to_index[self._db_atomic_numbers] = \ np.arange(len(self._db_atomic_numbers)) # Derivative of spline interpolation self.dF = _make_derivative(self.F) self.df = _make_derivative(self.f) self.drep = _make_derivative(self.rep) # Second derivative of spline interpolation self.ddF = _make_derivative(self.F, n=2) self.ddf = _make_derivative(self.f, n=2) self.ddrep = _make_derivative(self.rep, n=2) def energy_virial_and_forces(self, atomic_numbers_i, i_n, j_n, dr_nc, abs_dr_n): """ Compute the potential energy, the virial and the forces. Parameters ---------- atomic_numbers_i : array_like Atomic number for each atom in the system i_n, j_n : array_like Neighbor pairs dr_nc : array_like Distance vectors between neighbors abd_dr_n : array_like Length of distance vectors between neighbors Returns ------- epot : float Potential energy virial_v : array Virial forces_ic : array Forces acting on each atom """ nat = len(atomic_numbers_i) atnums_in_system = set(atomic_numbers_i) for atnum in atnums_in_system: if atnum not in self._db_atomic_numbers: raise RuntimeError('Element with atomic number {} found, but ' 'this atomic number has no EAM ' 'parametrization'.format(atnum)) # Density f_n = np.zeros_like(abs_dr_n) df_n = np.zeros_like(abs_dr_n) for atidx1, atnum1 in enumerate(self._db_atomic_numbers): f1 = self.f[atidx1] df1 = self.df[atidx1] mask1 = atomic_numbers_i[j_n]==atnum1 if mask1.sum() > 0: if type(f1) == list: for atidx2, atnum2 in enumerate(self._db_atomic_numbers): f = f1[atidx2] df = df1[atidx2] mask = np.logical_and(mask1, atomic_numbers_i[i_n]==atnum2) if mask.sum() > 0: f_n[mask] = f(abs_dr_n[mask]) df_n[mask] = df(abs_dr_n[mask]) else: f_n[mask1] = f1(abs_dr_n[mask1]) df_n[mask1] = df1(abs_dr_n[mask1]) density_i = np.bincount(i_n, weights=f_n, minlength=nat) # Repulsion rep_n = np.zeros_like(abs_dr_n) drep_n = np.zeros_like(abs_dr_n) for atidx1, atnum1 in enumerate(self._db_atomic_numbers): rep1 = self.rep[atidx1] drep1 = self.drep[atidx1] mask1 = atomic_numbers_i[i_n]==atnum1 if mask1.sum() > 0: for atidx2, atnum2 in enumerate(self._db_atomic_numbers): rep = rep1[atidx2] drep = drep1[atidx2] mask = np.logical_and(mask1, atomic_numbers_i[j_n]==atnum2) if mask.sum() > 0: r = rep(abs_dr_n[mask])/abs_dr_n[mask] rep_n[mask] = r drep_n[mask] = (drep(abs_dr_n[mask])-r)/abs_dr_n[mask] # Energy epot = 0.5*np.sum(rep_n) demb_i = np.zeros(nat) for atidx, atnum in enumerate(self._db_atomic_numbers): F = self.F[atidx] dF = self.dF[atidx] mask = atomic_numbers_i==atnum if mask.sum() > 0: epot += np.sum(F(density_i[mask])) demb_i[mask] += dF(density_i[mask]) # Forces reverse = find_indices_of_reversed_pairs(i_n, j_n, abs_dr_n) df_i_n = np.take(df_n, reverse) df_nc = -0.5*((demb_i[i_n]*df_n+demb_i[j_n]*df_i_n)+drep_n).reshape(-1,1)*dr_nc/abs_dr_n.reshape(-1,1) # Sum for each atom fx_i = np.bincount(j_n, weights=df_nc[:,0], minlength=nat) - \ np.bincount(i_n, weights=df_nc[:,0], minlength=nat) fy_i = np.bincount(j_n, weights=df_nc[:,1], minlength=nat) - \ np.bincount(i_n, weights=df_nc[:,1], minlength=nat) fz_i = np.bincount(j_n, weights=df_nc[:,2], minlength=nat) - \ np.bincount(i_n, weights=df_nc[:,2], minlength=nat) # Virial virial_v = -np.array([dr_nc[:,0]*df_nc[:,0], # xx dr_nc[:,1]*df_nc[:,1], # yy dr_nc[:,2]*df_nc[:,2], # zz dr_nc[:,1]*df_nc[:,2], # yz dr_nc[:,0]*df_nc[:,2], # xz dr_nc[:,0]*df_nc[:,1]]).sum(axis=1) # xy return epot, virial_v, np.transpose([fx_i, fy_i, fz_i]) def calculate(self, atoms, properties, system_changes): super().calculate(atoms, properties, system_changes) i_n, j_n, dr_nc, abs_dr_n = neighbour_list('ijDd', atoms, self._db_cutoff) epot, virial_v, forces_ic = self.energy_virial_and_forces(atoms.numbers, i_n, j_n, dr_nc, abs_dr_n) self.results.update({'energy': epot, 'free_energy': epot, 'stress': virial_v/atoms.get_volume(), 'forces': forces_ic}) def calculate_hessian_matrix(self, atoms, divide_by_masses=False): r"""Compute the Hessian matrix The Hessian matrix is the matrix of second derivatives of the potential energy :math:`\mathcal{V}_\mathrm{int}` with respect to coordinates, i.e.\ .. math:: \frac{\partial^2 \mathcal{V}_\mathrm{int}} {\partial r_{\nu{}i}\partial r_{\mu{}j}}, where the indices :math:`\mu` and :math:`\nu` refer to atoms and the indices :math:`i` and :math:`j` refer to the components of the position vector :math:`r_\nu` along the three spatial directions. The Hessian matrix has contributions from the pair potential and the embedding energy, .. math:: \frac{\partial^2 \mathcal{V}_\mathrm{int}}{\partial r_{\nu{}i}\partial r_{\mu{}j}} = \frac{\partial^2 \mathcal{V}_\mathrm{pair}}{ \partial r_{\nu i} \partial r_{\mu j}} + \frac{\partial^2 \mathcal{V}_\mathrm{embed}}{\partial r_{\nu i} \partial r_{\mu j}}. The contribution from the pair potential is .. math:: \frac{\partial^2 \mathcal{V}_\mathrm{pair}}{ \partial r_{\nu i} \partial r_{\mu j}} &= -\phi_{\nu\mu}'' \left( \frac{r_{\nu\mu i}}{r_{\nu\mu}} \frac{r_{\nu\mu j}}{r_{\nu\mu}} \right) -\frac{\phi_{\nu\mu}'}{r_{\nu\mu}}\left( \delta_{ij}- \frac{r_{\nu\mu i}}{r_{\nu\mu}} \frac{r_{\nu\mu j}}{r_{\nu\mu}} \right) \\ &+\delta_{\nu\mu}\sum_{\gamma\neq\nu}^{N} \phi_{\nu\gamma}'' \left( \frac{r_{\nu\gamma i}}{r_{\nu\gamma}} \frac{r_{\nu\gamma j}}{r_{\nu\gamma}} \right) +\delta_{\nu\mu}\sum_{\gamma\neq\nu}^{N}\frac{\phi_{\nu\gamma}'}{r_{\nu\gamma}}\left( \delta_{ij}- \frac{r_{\nu\gamma i}}{r_{\nu\gamma}} \frac{r_{\nu\gamma j}}{r_{\nu\gamma}} \right). The contribution of the embedding energy to the Hessian matrix is a sum of eight terms, .. math:: \frac{\mathcal{V}_\mathrm{embed}}{\partial r_{\mu j} \partial r_{\nu i}} &= T_1 + T_2 + T_3 + T_4 + T_5 + T_6 + T_7 + T_8 \\ T_1 &= \delta_{\nu\mu}U_\nu'' \sum_{\gamma\neq\nu}^{N}g_{\nu\gamma}'\frac{r_{\nu\gamma i}}{r_{\nu\gamma}} \sum_{\gamma\neq\nu}^{N}g_{\nu\gamma}'\frac{r_{\nu\gamma j}}{r_{\nu\gamma}} \\ T_2 &= -u_\nu''g_{\nu\mu}' \frac{r_{\nu\mu j}}{r_{\nu\mu}} \sum_{\gamma\neq\nu}^{N} G_{\nu\gamma}' \frac{r_{\nu\gamma i}}{r_{\nu\gamma}} \\ T_3 &= +u_\mu''g_{\mu\nu}' \frac{r_{\nu\mu i}}{r_{\nu\mu}} \sum_{\gamma\neq\mu}^{N} G_{\mu\gamma}' \frac{r_{\mu\gamma j}}{r_{\mu\gamma}} \\ T_4 &= -\left(u_\mu'g_{\mu\nu}'' + u_\nu'g_{\nu\mu}''\right) \left( \frac{r_{\nu\mu i}}{r_{\nu\mu}} \frac{r_{\nu\mu j}}{r_{\nu\mu}} \right)\\ T_5 &= \delta_{\nu\mu} \sum_{\gamma\neq\nu}^{N} \left(U_\gamma'g_{\gamma\nu}'' + U_\nu'g_{\nu\gamma}''\right) \left( \frac{r_{\nu\gamma i}}{r_{\nu\gamma}} \frac{r_{\nu\gamma j}}{r_{\nu\gamma}} \right) \\ T_6 &= -\left(U_\mu'g_{\mu\nu}' + U_\nu'g_{\nu\mu}'\right) \frac{1}{r_{\nu\mu}} \left( \delta_{ij}- \frac{r_{\nu\mu i}}{r_{\nu\mu}} \frac{r_{\nu\mu j}}{r_{\nu\mu}} \right) \\ T_7 &= \delta_{\nu\mu} \sum_{\gamma\neq\nu}^{N} \left(U_\gamma'g_{\gamma\nu}' + U_\nu'g_{\nu\gamma}'\right) \frac{1}{r_{\nu\gamma}} \left(\delta_{ij}- \frac{r_{\nu\gamma i}}{r_{\nu\gamma}} \frac{r_{\nu\gamma j}}{r_{\nu\gamma}} \right) \\ T_8 &= \sum_{\substack{\gamma\neq\nu \\ \gamma \neq \mu}}^{N} U_\gamma'' g_{\gamma\nu}'g_{\gamma\mu}' \frac{r_{\gamma\nu i}}{r_{\gamma\nu}} \frac{r_{\gamma\mu j}}{r_{\gamma\mu}} Parameters ---------- atoms : ase.Atoms divide_by_masses : bool Divide block :math:`\nu\mu` by :math:`m_\nu{}m_\mu{}` to obtain the dynamical matrix Returns ------- D : numpy.matrix Block Sparse Row matrix with the nonzero blocks Notes ----- Notation: * :math:`N` Number of atoms * :math:`\mathcal{V}_\mathrm{int}` Total potential energy * :math:`\mathcal{V}_\mathrm{pair}` Pair potential * :math:`\mathcal{V}_\mathrm{embed}` Embedding energy * :math:`r_{\nu{}i}` Component :math:`i` of the position vector of atom :math:`\nu` * :math:`r_{\nu\mu{}i} = r_{\mu{}i}-r_{\nu{}i}` * :math:`r_{\nu\mu{}}` Norm of :math:`r_{\nu\mu{}i}`, i.e.\ :math:`\left(r_{\nu\mu{}1}^2+r_{\nu\mu{}2}^2+r_{\nu\mu{}3}^2\right)^{1/2}` * :math:`\phi_{\nu\mu}(r_{\nu\mu{}})` Pair potential energy of atoms :math:`\nu` and :math:`\mu` * :math:`\rho_{\nu}` Total electron density of atom :math:`\nu` * :math:`U_\nu(\rho_nu)` Embedding energy of atom :math:`\nu` * :math:`g_{\delta}\left(r_{\gamma\delta}\right) \equiv g_{\gamma\delta}` Contribution from atom :math:`\delta` to :math:`\rho_\gamma` * :math:`m_\nu` mass of atom :math:`\nu` """ nat = len(atoms) atnums = atoms.numbers atnums_in_system = set(atnums) for atnum in atnums_in_system: if atnum not in atnums: raise RuntimeError('Element with atomic number {} found, but ' 'this atomic number has no EAM ' 'parametrization'.format(atnum)) # i_n: index of the central atom # j_n: index of the neighbor atom # dr_nc: distance vector between the two # abs_dr_n: norm of distance vector # Variable name ending with _n indicate arrays that contain # one element for each pair in the neighbor list. Names ending # with _i indicate arrays containing one element for each atom. i_n, j_n, dr_nc, abs_dr_n = neighbour_list('ijDd', atoms, self._db_cutoff) # Calculate derivatives of the pair energy drep_n = np.zeros_like(abs_dr_n) # first derivative ddrep_n = np.zeros_like(abs_dr_n) # second derivative for atidx1, atnum1 in enumerate(self._db_atomic_numbers): rep1 = self.rep[atidx1] drep1 = self.drep[atidx1] ddrep1 = self.ddrep[atidx1] mask1 = atnums[i_n]==atnum1 if mask1.sum() > 0: for atidx2, atnum2 in enumerate(self._db_atomic_numbers): rep = rep1[atidx2] drep = drep1[atidx2] ddrep = ddrep1[atidx2] mask = np.logical_and(mask1, atnums[j_n]==atnum2) if mask.sum() > 0: r = rep(abs_dr_n[mask])/abs_dr_n[mask] drep_n[mask] = (drep(abs_dr_n[mask])-r) / abs_dr_n[mask] ddrep_n[mask] = (ddrep(abs_dr_n[mask]) - 2.0 * drep_n[mask]) / abs_dr_n[mask] # Calculate electron density and its derivatives f_n = np.zeros_like(abs_dr_n) df_n = np.zeros_like(abs_dr_n) # first derivative ddf_n = np.zeros_like(abs_dr_n) # second derivative for atidx1, atnum1 in enumerate(self._db_atomic_numbers): f1 = self.f[atidx1] df1 = self.df[atidx1] ddf1 = self.ddf[atidx1] mask1 = atnums[j_n]==atnum1 if mask1.sum() > 0: if type(f1) == list: for atidx2, atnum2 in enumerate(self._db_atomic_numbers): f = f1[atidx2] df = df1[atidx2] ddf = ddf1[atidx2] mask = np.logical_and(mask1, atnums[i_n]==atnum2) if mask.sum() > 0: f_n[mask] = f(abs_dr_n[mask]) df_n[mask] = df(abs_dr_n[mask]) ddf_n[mask] = ddf(abs_dr_n[mask]) else: f_n[mask1] = f1(abs_dr_n[mask1]) df_n[mask1] = df1(abs_dr_n[mask1]) ddf_n[mask1] = ddf1(abs_dr_n[mask1]) # Accumulate density contributions density_i = np.bincount(i_n, weights=f_n, minlength=nat) # Calculate the derivatives of the embedding energy demb_i = np.zeros(nat) # first derivative ddemb_i = np.zeros(nat) # second derivative for atidx, atnum in enumerate(self._db_atomic_numbers): F = self.F[atidx] dF = self.dF[atidx] ddF = self.ddF[atidx] mask = atnums==atnum if mask.sum() > 0: demb_i[mask] += dF(density_i[mask]) ddemb_i[mask] += ddF(density_i[mask]) # There are two ways to divide the Hessian by atomic masses, either # during or after construction. The former is preferable with regard # to memory consumption. If we would divide by masses afterwards, # we would have to create a sparse matrix with the same size as the # Hessian matrix, i.e. we would momentarily need twice the given memory. if divide_by_masses: masses_i = atoms.get_masses().reshape(-1, 1, 1) geom_mean_mass_n = np.sqrt( np.take(masses_i, i_n) * np.take(masses_i, j_n) ).reshape(-1, 1, 1) else: masses_i = None geom_mean_mass_n = None #------------------------------------------------------------------------ # Calculate pair contribution to the Hessian matrix #------------------------------------------------------------------------ first_i = first_neighbours(nat, i_n) e_nc = (dr_nc.T / abs_dr_n).T # normalized distance vectors r_i^{\mu\nu} outer_e_ncc = e_nc.reshape(-1, 3, 1) * e_nc.reshape(-1, 1, 3) eye_minus_outer_e_ncc = np.eye(3, dtype=e_nc.dtype) - outer_e_ncc D = self._calculate_hessian_pair_term( nat, i_n, j_n, abs_dr_n, first_i, drep_n, ddrep_n, outer_e_ncc, eye_minus_outer_e_ncc, divide_by_masses, geom_mean_mass_n, masses_i ) drep_n = None ddrep_n = None #------------------------------------------------------------------------ # Calculate contribution of embedding term #------------------------------------------------------------------------ # For each pair in the neighborlist, create arrays which store the # derivatives of the embedding energy of the corresponding atoms. demb_i_n = np.take(demb_i, i_n) demb_j_n = np.take(demb_i, j_n) # Let r be an index into the neighbor list. df_n[r] contains the the # contribution from atom j_n[r] to the derivative of the electron # density of atom i_n[r]. We additionally need the contribution of # i_n[r] to the derivative of j_n[r]. This value is also in df_n, # but at a different position. reverse[r] gives the new index s # where we find this value. The same indexing applies to ddf_n. reverse = find_indices_of_reversed_pairs(i_n, j_n, abs_dr_n) df_i_n = np.take(df_n, reverse) ddf_i_n = np.take(ddf_n, reverse) #we already have ddf_j_n = ddf_n reverse = None df_n_e_nc_outer_product = (df_n * e_nc.T).T df_e_ni = np.empty((nat, 3), dtype=df_n.dtype) for x in range(3): df_e_ni[:, x] = np.bincount( i_n, weights=df_n_e_nc_outer_product[:, x], minlength=nat ) df_n_e_nc_outer_product = None D += self._calculate_hessian_embedding_term_1( nat, ddemb_i, df_e_ni, divide_by_masses, masses_i ) D += self._calculate_hessian_embedding_term_2( nat, j_n, first_i, ddemb_i, df_i_n, e_nc, df_e_ni, divide_by_masses, geom_mean_mass_n ) D += self._calculate_hessian_embedding_term_3( nat, i_n, j_n, first_i, ddemb_i, df_n, e_nc, df_e_ni, divide_by_masses, geom_mean_mass_n ) df_e_ni = None D += self._calculate_hessian_embedding_terms_4_and_5( nat, first_i, i_n, j_n, outer_e_ncc, demb_i_n, demb_j_n, ddf_i_n, ddf_n, divide_by_masses, masses_i, geom_mean_mass_n ) outer_e_ncc = None ddf_i_n = None ddf_n = None D += self._calculate_hessian_embedding_terms_6_and_7( nat, i_n, j_n, first_i, abs_dr_n, eye_minus_outer_e_ncc, demb_i_n, demb_j_n, df_n, df_i_n, divide_by_masses, masses_i, geom_mean_mass_n ) eye_minus_outer_e_ncc = None df_n = None demb_i_n = None demb_j_n = None abs_dr_n = None D += self._calculate_hessian_embedding_term_8( nat, i_n, j_n, e_nc, ddemb_i, df_i_n, divide_by_masses, masses_i, geom_mean_mass_n ) return D def get_hessian(self, atoms, format='sparse', divide_by_masses=False): H = self.calculate_hessian_matrix(atoms, divide_by_masses=divide_by_masses) if format == 'dense': H = H.todense() return H def _calculate_hessian_pair_term( self, nat, i_n, j_n, abs_dr_n, first_i, drep_n, ddrep_n, outer_e_ncc, eye_minus_outer_e_ncc, divide_by_masses=False, geom_mean_mass_n=None, masses_i=None): """Calculate the pair energy contribution to the Hessian. Parameters ---------- nat : int number of atoms i_n, j_n : array_like Neighbor pairs abs_dr_n : array_like Length of distance vectors between neighbors first_i : array_like Indices in :code:`i_n` where contiguous blocks with the same value start drep_n : array_like First derivative of the pair energy with respect to distance vectors between neighbors ddrep_n : array_like Second derivative of the pair energy with respect to distance vectors between neighbors outer_e_ncc : array_like outer product of normalized distance vectors eye_minus_outer_e_ncc : array_like identity matrix minus outer product of normalized distance vectors Returns ------- D : scipy.sparse.bsr_matrix """ D_ncc = -(ddrep_n * outer_e_ncc.T).T D_ncc += -(drep_n / abs_dr_n * eye_minus_outer_e_ncc.T).T if divide_by_masses: D = bsr_matrix( (D_ncc / geom_mean_mass_n, j_n, first_i), shape=(3*nat, 3*nat) ) else: D = bsr_matrix((D_ncc, j_n, first_i), shape=(3*nat, 3*nat)) Ddiag = np.empty((nat, 3, 3)) for x in range(3): for y in range(3): Ddiag[:, x, y] = -np.bincount(i_n, weights=D_ncc[:, x, y]) # summation if divide_by_masses: Ddiag /= masses_i # put 3x3 blocks on diagonal (Kronecker Delta delta_{\mu\nu}) D += bsr_matrix((Ddiag, np.arange(nat), np.arange(nat+1)), shape=(3*nat, 3*nat)) return D def _calculate_hessian_embedding_term_1(self, nat, ddemb_i, df_e_ni, divide_by_masses=False, masses_i=None, symmetry_check=False): r"""Calculate term 1 in the embedding part of the Hessian matrix. .. math:: T_{\nu\mu}^{(1)} = \delta_{\nu\mu}U_\nu'' \sum_{\gamma\neq\nu}^{\natoms}g_{\nu\gamma}'\frac{r_{\nu\gamma i}}{r_{\nu\gamma}} \sum_{\gamma\neq\nu}^{\natoms}g_{\nu\gamma}'\frac{r_{\nu\gamma j}}{r_{\nu\gamma}} This term is likely zero in equilibrium because the sum is zero (appears in the force vector). Parameters ---------- nat : int Number of atoms ddemb_i : array_like Second derivative of the embedding energy df_e_ni : array_like First derivative of the electron density times the normalized distance vector between neighbors divide_by_masses : bool Divide term by geometric mean of mass of pairs of atoms to obtain the contribution to the dynamical matrix masses_i : array_like masses of atoms :code:`i` symmetry_check : bool Check if the term is symmetric Returns ------- D : scipy.sparse.bsr_matrix """ term_1_ncc = ((ddemb_i * df_e_ni.T).T).reshape(-1,3,1) * df_e_ni.reshape(-1,1,3) if divide_by_masses: term_1_ncc /= masses_i term_1 = bsr_matrix((term_1_ncc, np.arange(nat), np.arange(nat+1)), shape=(3*nat, 3*nat)) if symmetry_check: print("check term 1", np.linalg.norm(term_1.todense() - term_1.todense().T)) return term_1 def _calculate_hessian_embedding_term_2(self, nat, j_n, first_i, ddemb_i, df_i_n, e_nc, df_e_ni, divide_by_masses=False, geom_mean_mass_n=None, symmetry_check=False): r"""Calculate term 2 in the embedding part of the Hessian matrix. .. math:: T_{\nu\mu}^{(2)} = -u_\nu''g_{\nu\mu}' \frac{r_{\nu\mu j}}{r_{\nu\mu}} \sum_{\gamma\neq\nu}^{\natoms} g_{\nu\gamma}' \frac{r_{\nu\gamma i}}{r_{\nu\gamma}} This term is likely zero in equilibrium because the sum is zero (appears in the force vector). Parameters ---------- nat : int Number of atoms j_n : array_like Indices of neighbor atoms first_i : array_like Indices in :code:`i_n` where contiguous blocks with the same value start ddemb_i : array_like Second derivative of the embedding energy df_i_n : array_like Derivative of the electron density of atom :code:`j` with respect to the distance to atom :code:`i` e_nc : array_like Normalized distance vectors between neighbors df_e_ni : array_like First derivative of the electron density times the normalized distance vector between neighbors divide_by_masses : bool Divide term by geometric mean of mass of pairs of atoms to obtain the contribution to the dynamical matrix masses_i : array_like masses of atoms :code:`i` geom_mean_mass_n : array_like geometric mean of masses of pairs of atoms symmetry_check : bool Check if the term is symmetric Returns ------- D : scipy.sparse.bsr_matrix """ df_n_e_nc_j_n = np.take(df_e_ni, j_n, axis=0) ddemb_j_n = np.take(ddemb_i, j_n) term_2_ncc = ((ddemb_j_n * df_i_n * e_nc.T).T).reshape(-1,3,1) * df_n_e_nc_j_n.reshape(-1,1,3) if divide_by_masses: term_2_ncc /= geom_mean_mass_n term_2 = bsr_matrix((term_2_ncc, j_n, first_i), shape=(3*nat, 3*nat)) if symmetry_check: print("check term 2", np.linalg.norm(term_2.todense() - term_2.todense().T)) return term_2 def _calculate_hessian_embedding_term_3(self, nat, i_n, j_n, first_i, ddemb_i, df_n, e_nc, df_e_ni, divide_by_masses=False, geom_mean_mass_n=None, symmetry_check=False): r"""Calculate term 3 in the embedding part of the Hessian matrix. .. math:: T_{\nu\mu}^{(3)} = +u_\mu''g_{\mu\nu}' \frac{r_{\nu\mu i}}{r_{\nu\mu}} \sum_{\gamma\neq\mu}^{\natoms} g_{\mu\gamma}' \frac{r_{\mu\gamma j}}{r_{\mu\gamma}} This term is likely zero in equilibrium because the sum is zero (appears in the force vector). Parameters ---------- nat : int Number of atoms i_n, j_n : array_like Neighbor pairs first_i : array_like Indices in :code:`i_n` where contiguous blocks with the same value start ddemb_i : array_like Second derivative of the embedding energy df_n : array_like Derivative of the electron density of atom :code:`i` with respect to the distance to atom :code:`j` e_nc : array_like Normalized distance vectors between neighbors df_e_ni : array_like First derivative of the electron density times the normalized distance vector between neighbors divide_by_masses : bool Divide term by geometric mean of mass of pairs of atoms to obtain the contribution to the dynamical matrix masses_i : array_like masses of atoms :code:`i` geom_mean_mass_n : array_like geometric mean of masses of pairs of atoms symmetry_check : bool Check if the term is symmetric Returns ------- D : scipy.sparse.bsr_matrix """ # Likely zero in equilibrium because the sum is zero (appears in the force vector) df_e_ni_n = np.take(df_e_ni, i_n, axis=0) ddemb_i_n = np.take(ddemb_i, i_n) term_3_ncc = -((ddemb_i_n * df_n * df_e_ni_n.T).T).reshape(-1,3,1) * e_nc.reshape(-1,1,3) if divide_by_masses: term_3_ncc /= geom_mean_mass_n term_3 = bsr_matrix((term_3_ncc, j_n, first_i), shape=(3*nat, 3*nat)) if symmetry_check: print("check term 3", np.linalg.norm(term_3.todense() - term_3.todense().T)) return term_3 def _calculate_hessian_embedding_terms_4_and_5( self, nat, first_i, i_n, j_n, outer_e_ncc, demb_i_n, demb_j_n, ddf_i_n, ddf_n, divide_by_masses=False, masses_i=None, geom_mean_mass_n=None, symmetry_check=False): r"""Calculate term 4 and 5 in the embedding part of the Hessian matrix. .. math:: T_{\nu\mu}^{(4)} &= -\left(u_\mu'g_{\mu\nu}'' + u_\nu'g_{\nu\mu}''\right) \left( \frac{r_{\nu\mu i}}{r_{\nu\mu}} \frac{r_{\nu\mu j}}{r_{\nu\mu}} \right)\\ T_{\nu\mu}^{(5)} &= \delta_{\nu\mu} \sum_{\gamma\neq\nu}^{N} \left(U_\gamma'g_{\gamma\nu}'' + U_\nu'g_{\nu\gamma}''\right) \left( \frac{r_{\nu\gamma i}}{r_{\nu\gamma}} \frac{r_{\nu\gamma j}}{r_{\nu\gamma}} \right) Parameters ---------- nat : int Number of atoms i_n, j_n : array_like Neighbor pairs first_i : array_like Indices in :code:`i_n` where contiguous blocks with the same value start ddemb_i : array_like Second derivative of the embedding energy df_n : array_like Derivative of the electron density of atom :code:`i` with respect to the distance to atom :code:`j` e_nc : array_like Normalized distance vectors between neighbors df_e_ni : array_like First derivative of the electron density times the normalized distance vector between neighbors divide_by_masses : bool Divide term by geometric mean of mass of pairs of atoms to obtain the contribution to the dynamical matrix masses_i : array_like masses of atoms :code:`i` geom_mean_mass_n : array_like geometric mean of masses of pairs of atoms symmetry_check : bool Check if the terms are symmetric Returns ------- D : scipy.sparse.bsr_matrix """ tmp_1 = -((demb_j_n * ddf_i_n + demb_i_n * ddf_n) * outer_e_ncc.T).T # We don't immediately add term 4 to the matrix, because it would have # to be normalized by the masses if divide_by_masses is true. However, # for construction of term 5, we need term 4 without normalization tmp_1_summed = np.empty((nat, 3, 3), dtype=tmp_1.dtype) for x in range(3): for y in range(3): tmp_1_summed[:, x, y] = -np.bincount(i_n, weights=tmp_1[:, x, y]) if divide_by_masses: tmp_1_summed /= masses_i term_5 = bsr_matrix((tmp_1_summed, np.arange(nat), np.arange(nat+1)), shape=(3*nat, 3*nat)) if symmetry_check: print("check term 5", np.linalg.norm(term_5.todense() - term_5.todense().T)) if divide_by_masses: tmp_1 /= geom_mean_mass_n term_4 = bsr_matrix((tmp_1, j_n, first_i), shape=(3*nat, 3*nat)) if symmetry_check: print("check term 4", np.linalg.norm(term_4.todense() - term_4.todense().T)) return term_4 + term_5 def _calculate_hessian_embedding_terms_6_and_7( self, nat, i_n, j_n, first_i, abs_dr_n, eye_minus_outer_e_ncc, demb_i_n, demb_j_n, df_n, df_i_n, divide_by_masses=False, masses_i=None, geom_mean_mass_n=None, symmetry_check=False): r"""Calculate term 6 and 7 in the embedding part of the Hessian matrix. .. math:: T_{\nu\mu}^{(6)} &= -\left(U_\mu'g_{\mu\nu}' + U_\nu'g_{\nu\mu}'\right) \frac{1}{r_{\nu\mu}} \left( \delta_{ij}- \frac{r_{\nu\mu i}}{r_{\nu\mu}} \frac{r_{\nu\mu j}}{r_{\nu\mu}} \right) \\ T_{\nu\mu}^{(7)}&= \delta_{\nu\mu} \sum_{\gamma\neq\nu}^{N} \left(U_\gamma'g_{\gamma\nu}' + U_\nu'g_{\nu\gamma}'\right) \frac{1}{r_{\nu\gamma}} \left(\delta_{ij}- \frac{r_{\nu\gamma i}}{r_{\nu\gamma}} \frac{r_{\nu\gamma j}}{r_{\nu\gamma}} \right) Parameters ---------- nat : int Number of atoms i_n, j_n : array_like Neighbor pairs first_i : array_like Indices in :code:`i_n` where contiguous blocks with the same value start abs_dr_n : array_like Length of distance vectors between neighbors eye_minus_outer_e_ncc : array_like identity matrix minus outer product of normalized distance vectors demb_i_n : array_like First derivative of the embedding energy for atoms in the neighbor list demb_j_n : array_like First derivative of the embedding energy of neighbor atoms in the neighbor list df_n : array_like Derivative of the electron density of atom :code:`i` with respect to the distance to atom :code:`j` df_i_n : array_like Derivative of the electron density of atom :code:`j` with respect to the distance to atom :code:`i` divide_by_masses : bool Divide term by geometric mean of mass of pairs of atoms to obtain the contribution to the dynamical matrix masses_i : array_like masses of atoms :code:`i` geom_mean_mass_n : array_like geometric mean of masses of pairs of atoms symmetry_check : bool Check if the terms are symmetric Returns ------- D : scipy.sparse.bsr_matrix """ # Like term 4, which was needed to construct term 5, we don't add # term 6 immediately, because it is needed for construction of term 7 tmp_2 = -((demb_j_n * df_i_n + demb_i_n * df_n) / abs_dr_n * eye_minus_outer_e_ncc.T).T tmp_2_summed = np.empty((nat, 3, 3), dtype=tmp_2.dtype) for x in range(3): for y in range(3): tmp_2_summed[:, x, y] = -np.bincount(i_n, weights=tmp_2[:, x, y]) if divide_by_masses: tmp_2_summed /= masses_i term_7 = bsr_matrix((tmp_2_summed, np.arange(nat), np.arange(nat+1)), shape=(3*nat, 3*nat)) if symmetry_check: print("check term 7", np.linalg.norm(term_7.todense() - term_7.todense().T)) if divide_by_masses: tmp_2 /= geom_mean_mass_n term_6 = bsr_matrix((tmp_2, j_n, first_i), shape=(3*nat, 3*nat)) if symmetry_check: print("check term 6", np.linalg.norm(term_6.todense() - term_6.todense().T)) return term_6 + term_7 def _calculate_hessian_embedding_term_8(self, nat, i_n, j_n, e_nc, ddemb_i, df_i_n, divide_by_masses=False, masses_i=None, geom_mean_mass_n=None, symmetry_check=False): r"""Calculate term 8 in the embedding part of the Hessian matrix. .. math:: T_{\nu\mu}^{(8)} = \sum_{\substack{\gamma\neq\nu \\ \gamma \neq \mu}}^{N} U_\gamma'' g_{\gamma\nu}'g_{\gamma\mu}' \frac{r_{\gamma\nu i}}{r_{\gamma\nu}} \frac{r_{\gamma\mu j}}{r_{\gamma\mu}} This term requires knowledge of common neighbors of pairs of atoms. Parameters ---------- nat : int Number of atoms i_n, j_n : array_like Neighbor pairs first_i : array_like Indices in :code:`i_n` where contiguous blocks with the same value start ddemb_i : array_like Second derivative of the embedding energy e_nc : array_like Normalized distance vectors between neighbors df_i_n : array_like Derivative of the electron density of atom :code:`j` with respect to the distance to atom :code:`i` divide_by_masses : bool Divide term by geometric mean of mass of pairs of atoms to obtain the contribution to the dynamical matrix masses_i : array_like masses of atoms :code:`i` geom_mean_mass_n : array_like geometric mean of masses of pairs of atoms symmetry_check : bool Check if the terms are symmetric Returns ------- D : scipy.sparse.bsr_matrix """ cnl_i1_i2, cnl_j1, nl_index_i1_j1, nl_index_i2_j1 = find_common_neighbours(i_n, j_n, nat) unique_pairs_i1_i2, bincount_bins = np.unique(cnl_i1_i2, axis=0, return_inverse=True) cnl_i1_i2 = None tmp_3 = np.take(df_i_n, nl_index_i1_j1) * np.take(ddemb_i, cnl_j1) * np.take(df_i_n, nl_index_i2_j1) cnl_j1 = None tmp_3_summed = np.empty((unique_pairs_i1_i2.shape[0], 3, 3), dtype=e_nc.dtype) for x, y in np.ndindex(3, 3): weights = (tmp_3 * np.take(e_nc[:, x], nl_index_i1_j1) * np.take(e_nc[:, y], nl_index_i2_j1) ) tmp_3_summed[:, x, y] = np.bincount( bincount_bins, weights=weights, minlength=unique_pairs_i1_i2.shape[0] ) nl_index_i1_j1 = None nl_index_i2_j1 = None weights = None tmp_3 = None bincount_bins = None if divide_by_masses: geom_mean_mass_i1_i2 = np.sqrt( np.take(masses_i, unique_pairs_i1_i2[:, 0]) * np.take(masses_i, unique_pairs_i1_i2[:, 1]) ) tmp_3_summed /= geom_mean_mass_i1_i2[:, np.newaxis, np.newaxis] index_ptr = first_neighbours(nat, unique_pairs_i1_i2[:, 0]) term_8 = bsr_matrix((tmp_3_summed, unique_pairs_i1_i2[:, 1], index_ptr), shape=(3*nat, 3*nat)) if symmetry_check: print("check term 8", np.linalg.norm(term_8.todense() - term_8.todense().T)) return term_8 @property def cutoff(self): return self._db_cutoff
40,013
41.164384
143
py
matscipy
matscipy-master/matscipy/calculators/eam/average_atom.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2020 Wolfram G. Nöhring (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # from .io import EAMParameters import numpy as np def average_potential( concentrations, parameters, F, f, rep, kind="eam/alloy", avg_atom="A", atomic_number=999, crystal_structure="unknown", lattice_constant=1.0, ): r"""Generate Average-atom potential The Average-atom (A-atom) potential is a mean-field approximation for random alloys, see Ref. `1`_. The purpose is to replace the true elements by a single fictious element, the A-atom. A configuration of A-atoms yields approximately the same potential energy as the corresponding random alloy configuration. Other average material properties, e.g. the elastic constants, are reproduced as well. For a full derivation, see Ref. `1`. The A-atom potential has standard EAM form, i.e. it can be tabulated just like any other EAM potential. The potential functions are simply the concentration-weighted averages of the pure element functions: .. math:: \phi_{AA}\left(r_{\gamma\delta}\right) &= \sum_{X}^{N_T}\sum_{Y}^{N_T} c_{X}c_{Y} \phi_{XY}\left(r_{\gamma\delta}\right) \quad\text{(pair potential)}, \\ U_{A}\left(\rho_\gamma\right) &= \sum_{X}^{N_T}c_{X}U_{X}\left(\rho_\gamma\right) \quad\text{(embedding energy)}, \\ g_A\left(r_{\gamma\delta}\right) &= \sum_{X}^{N_T}c_X g_X\left(r_{\gamma\delta}\right)\quad\text{(electron density)},\;\text{and}\\ m_A &= \sum_{X}^{N_T}c_X m_X\quad\text{(mass)}. .. note:: Currently, only eam/alloy-style potentials can be averaged. The extension to eam/fs should be straightforward, however. Parameters ---------- concentrations: array_like concentrations of the elements in the A-atom parameters: EAMParameters EAM potential parameters F : array_like tabulated embedding energy functionals f : array_like tabulated electron density functions rep : array_like tabulated pair potential energy functions Returns ------- parameters : EAMParameters EAM potential parameters new_F : array_like tabulated embedding energy functionals, including A-atom functional new_f : array_like tabulated electron density functions, including A-atom function(s) new_rep : array_like tabulated pair potential energy functions, including pairs with A-atom Examples -------- >>> from matscipy.calculators.eam import io, average_atom >>> source, parameters, F, f, rep = io.read_eam( >>> "ZrCu.onecolumn.eam.alloy" >>> ) >>> concentrations = [0.5, 0.5] >>> (new_parameters, new_F, new_f, new_rep) = average_atom.average_potential( >>> concentrations, parameters, F, f, rep >>> ) >>> composition = " ".join( >>> [str(c * 100.0) + "% {0},".format(e) for c, e in zip(concentrations, parameters.symbols)] >>> ) >>> composition = composition.rstrip(",") >>> source += ", averaged for composition {0}".format(composition) >>> io.write_eam( >>> source, >>> new_parameters, >>> new_F, >>> new_f, >>> new_rep, >>> "ZrCu.onecolumn.averaged.eam.alloy", >>> kind="eam/alloy", >>> ) Read an EAM potential table for two elements in eam/alloy format, and create a new table with additional A-atom functions for the equicomposition alloy. References ---------- .. [1] Varvenne, C., Luque, A., Nöhring, W. G. & Curtin, W. A. Average-atom interatomic potential for random alloys. Physical Review B 93, 104201 (2016). Notes ----- Notation: * :math:`N` Number of atoms * :math:`N_T` Number of elements * :math:`r_{\nu\mu{}}` Pair distance of atoms :math:`\nu` and :math:`\mu` * :math:`\phi_{\nu\mu}(r_{\nu\mu{}})` Pair potential energy of atoms :math:`\nu` and :math:`\mu` * :math:`\rho_{\nu}` Total electron density of atom :math:`\nu` * :math:`U_\nu(\rho_nu)` Embedding energy of atom :math:`\nu` * :math:`g_{\delta}\left(r_{\gamma\delta}\right) \equiv g_{\gamma\delta}` Contribution from atom :math:`\delta` to :math:`\rho_\gamma` * :math:`m_\nu` mass of atom :math:`\nu` """ if kind == "eam" or kind == "eam/fs": raise NotImplementedError assert np.isclose(np.sum(concentrations), 1) symbols = [s for s in parameters.symbols] + [avg_atom] atomic_numbers = np.r_[parameters.atomic_numbers, atomic_number] atomic_masses = np.r_[ parameters.atomic_masses, np.average(parameters[2], weights=concentrations) ] lattice_constants = np.r_[parameters.lattice_constants, lattice_constant] crystal_structures = np.r_[ parameters.crystal_structures, np.array(crystal_structure) ] new_parameters = EAMParameters( symbols, atomic_numbers, atomic_masses, lattice_constants, crystal_structures, parameters.number_of_density_grid_points, parameters.number_of_distance_grid_points, parameters.density_grid_spacing, parameters.distance_grid_spacing, parameters.cutoff, ) # Average embedding energy and electron density functions new_F = np.r_[F, np.zeros((1, F.shape[1]), dtype=F.dtype)] new_f = np.r_[f, np.zeros((1, f.shape[1]), dtype=f.dtype)] new_F[-1, :] = np.average(F, axis=0, weights=concentrations) new_f[-1, :] = np.average(f, axis=0, weights=concentrations) # Average the pair potential new_rep = np.concatenate( (rep, np.zeros((rep.shape[0], 1, rep.shape[2]), dtype=rep.dtype)), axis=1 ) new_rep = np.concatenate( (new_rep, np.zeros((1, new_rep.shape[1], rep.shape[2]), dtype=rep.dtype)), axis=0, ) # Consider the matrix Vij of pair functions # i: rows, each corresponding to an element # j: columns, each corresponding to an element # Each element corresponds to the function # for the atom pair i,j # # Compute the last row of the new Vij matrix, excluding the # value on the diagonal. Each column j corresponds to the # interaction of a particular type j with the homogenous material. new_rep[-1, :-1, :] = np.average(rep, axis=0, weights=concentrations) new_rep[:-1, -1, :] = new_rep[-1, :-1, :] # Compute the last potential on the diagonal. This is the # interaction of the homogeneous material with itself. column = new_rep[:-1, -1, :] new_rep[-1, -1, :] = np.average(column, axis=0, weights=concentrations) return new_parameters, new_F, new_f, new_rep
7,505
37.295918
139
py
matscipy
matscipy-master/matscipy/electrochemistry/poisson_boltzmann_distribution.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """ Calculate ionic densities consistent with the Poisson-Boltzmann equation. Copyright 2019, 2020 IMTEK Simulation University of Freiburg Authors: Johannes Hoermann <[email protected]> Lukas Elflein <[email protected]> """ import numpy as np import scipy.constants as sc import decimal np.random.seed(74) def ionic_strength(c, z): """Compute ionic strength from charges and concentrations Parameters ---------- c : (M,) ndarray M bulk concentrations [concentration unit, i.e. mol m^-3] z : (M,) ndarray M number charges [number charge unit, i.e. 1] Returns ------- I : float ionic strength ( 1/2 * sum(z_i^2*c_i) ) [concentration unit, i.e. mol m^-3] """ return 0.5*np.sum(np.square(z) * c) def debye(c, z, T=298.15, relative_permittivity=79, vacuum_permittivity=sc.epsilon_0, R=sc.value('molar gas constant'), F=sc.value('Faraday constant')): """Calculate the Debye length (in SI units per default). The Debye length indicates at which distance a charge will be screened off. Parameters ---------- c : (M,) ndarray bulk concentrations of each ionic species [mol/m^3] z : (M,) ndarray charge of each ionic species [1] T : float temperature of the solution [K] (default: 298.15) relative_permittivity: float relative permittivity of the ionic solution [1] (default: 79) vacuum_permittivity: float vacuum permittivity [F m^-1] (default: 8.854187817620389e-12 ) R : float molar gas constant [J mol^-1 K^-1] (default: 8.3144598) F : float Faraday constant [C mol^-1] (default: 96485.33289) Returns ------- lambda_D : float Debye length, sqrt( epsR*eps*R*T/(2*F^2*I) ) [m] """ I = ionic_strength(c, z) return np.sqrt(relative_permittivity*vacuum_permittivity*R*T/(2.0*F**2*I)) def gamma(u, T=298.15): """Calculate term from Gouy-Chapmann theory. Parameters ---------- u: float electrostatic potential at the metal/solution boundary in Volts, e.g. 0.05 [V] T: float temperature of the solution in Kelvin [K] (default: 298.15) Returns ------- float """ product = sc.value('Faraday constant') * u / (4 * sc.value('molar gas constant') * T) return np.tanh(product) def potential(x, c, z, u, T=298.15, relative_permittivity=79): """The potential near a charged surface in an ionic solution. A single value is returned, which specifies the value of the potential at this distance. The decimal package is used for increased precision. If only normal float precision is used, the potential is a step function. Steps in the potential result in unphysical particle concentrations. Parameters --------- x : (N,) ndarray z-distance from the surface [m] c : (M,) ndarray bulk concentrations of each ionic species [mol/m^3] z : (M,) ndarray charge number of each ionic species [1] u: float electrostatic potential at the metal/solution boundary in Volts, e.g. 0.05 [V] T : float temperature of the solution [Kelvin] (default: 298.15) relative_permittivity: float relative permittivity of the ionic solution [] (default: 79) Returns ------- phi: (N,) ndarray Electrostatic potential [V] """ # Calculate the term in front of the log, containing a bunch of constants prefactor = 2 * sc.value('molar gas constant') * T / sc.value('Faraday constant') # For the later calculations we need the debye length debye_value = debye(c, z, T, relative_permittivity) kappa = 1 / debye_value # We also need to evaluate the gamma function gamma_value = gamma(u, T) # The e^{-kz} term exponential = np.exp(-kappa * x) # The fraction inside the log numerator = 1.0 + gamma_value * exponential divisor = 1.0 - gamma_value * exponential # This is the complete term for the potential phi = prefactor * np.log(numerator / divisor) # Convert to float again for better handling in plotting etc. # phi = float(phi) return phi def concentration(x, c, z, u, T=298.15, relative_permittivity=79): """The concentration of ions near a charged surface. Calculates the molar concentration of ions of a species, at a distance x away from a substrate/solution interface. Potential difference u between substrate and bulk solution leads to non-neutrality close to the interface, with concentrations converging to their bulk values at high distances. Parameters ---------- x : (N,) ndarray distance from the surface [m] c : (M,) ndarray bulk concentrations (i.e. far from the surface) [mol/m^-3] z : (M,) ndarray number charge of each ionic species [1] u : float electrostatic potential at the metal/liquid interface against bulk [V] T : float temperature of the solution [K] (default: 298.15) relative_permittivity : float relative permittivity of the ionic solution, 80 for water [1] Returns ------- c : (M,N) ndarray molar concentrations of ion species [mol/m^3] """ # Evaluate the potential at the current location potential_value = potential(x, c, z, u, T, relative_permittivity) phi_z = np.outer(potential_value, np.array(z)) # N x M matrix (rows, cols) f = sc.value('Faraday constant') / (sc.value('molar gas constant') * T) # The concentration is an exponential function of the potential C = np.exp(- f * phi_z) # The concentration is scaled relative to the bulk concentration C *= c return C.T # M x N matrix (rows, cols) def charge_density(x, c, z, u, T=298.15, relative_permittivity=79): """ Charge density due to Poisson-Boltzmann distribution Parameters ---------- x : (N,) ndarray distance from the surface [m] c : (M,) ndarray bulk concentrations (i.e. far from the surface) [mol/m^-3] z : (M,) ndarray number charge of each ionic species [1] u : float electrostatic potential at the metal/liquid interface against bulk [V] T : float temperature of the solution [K] (default: 298.15) relative_permittivity : float relative permittivity of the ionic solution, 80 for water [1] Returns ------- c : (N,) ndarray charge density [C/m^3] """ C = concentration(x, c, z, u, T, relative_permittivity) return sc.value("Faraday constant") * np.sum(C.T*z, axis=1) def test(): """Run docstring unittests""" import doctest doctest.testmod() def main(): """Do stuff.""" print('Done.') if __name__ == '__main__': # Run doctests test() # Execute everything else main()
7,718
29.630952
92
py
matscipy
matscipy-master/matscipy/electrochemistry/steric_correction.py
# # Copyright 2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """Enforces minimum distances on coordinates within discrete distribtution. Copyright 2020 IMTEK Simulation University of Freiburg Authors: Johannes Hoermann <[email protected]> Examples ------- Benchmark different scipy optimizers for the steric correction problem: >>> # measures of box >>> xsize = ysize = 5e-9 # nm, SI units >>> zsize = 10e-9 # nm, SI units >>> >>> # get continuum distribution, z direction >>> x = np.linspace(0, zsize, 2000) >>> c = [0.1,0.1] >>> z = [1,-1] >>> u = 0.05 >>> >>> phi = potential(x, c, z, u) >>> C = concentration(x, c, z, u) >>> rho = charge_density(x, c, z, u) >>> >>> # create distribution functions >>> distributions = [interpolate.interp1d(x,c) for c in C] >>> >>> # sample discrete coordinate set >>> box = np.array([xsize, ysize, zsize])m >>> sample_size = 100 >>> >>> samples = [ continuous2discrete( >>> distribution=d, box=box, count=sample_size) for d in distributions ] >>> >>> # apply penalty for steric overlap >>> x = np.vstack(samples) >>> >>> box = np.array([[0.,0.,0],box]) # needs lower corner >>> >>> n = x.shape[0] >>> dim = x.shape[1] >>> >>> # benchmark methods >>> mindsq, (p1,p2) = scipy_distance_based_closest_pair(x) >>> pmin = np.min(x,axis=0) >>> pmax = np.max(x,axis=0) >>> mind = np.sqrt(mindsq) >>> logger.info("Minimum pair-wise distance in sample: {}".format(mind)) >>> logger.info("First sample point in pair: ({:8.4e},{:8.4e},{:8.4e})".format(*p1)) >>> logger.info("Second sample point in pair ({:8.4e},{:8.4e},{:8.4e})".format(*p2)) >>> logger.info("Box lower boundary: ({:8.4e},{:8.4e},{:8.4e})".format(*box[0])) >>> logger.info("Minimum coordinates in sample: ({:8.4e},{:8.4e},{:8.4e})".format(*pmin)) >>> logger.info("Maximum coordinates in sample: ({:8.4e},{:8.4e},{:8.4e})".format(*pmax)) >>> logger.info("Box upper boundary: ({:8.4e},{:8.4e},{:8.4e})".format(*box[1])) >>> >>> # stats: method, x, res, dt, mind, p1, p2 , pmin, pmax >>> stats = [('initial',x,None,0,mind,p1,p2,pmin,pmax)] >>> >>> r = 4e-10 # 4 Angstrom steric radius >>> logger.info("Steric radius: {:8.4e}".format(r)) >>> >>> methods = [ >>> 'Powell', >>> 'CG', >>> 'BFGS', >>> 'L-BFGS-B' >>> ] >>> >>> for m in methods: >>> try: >>> logger.info("### {} ###".format(m)) >>> t0 = time.perf_counter() >>> x1, res = apply_steric_correction(x,box=box,r=r,method=m) >>> t1 = time.perf_counter() >>> dt = t1 - t0 >>> logger.info("{} s runtime".format(dt)) >>> >>> mindsq, (p1,p2) = scipy_distance_based_closest_pair(x1) >>> mind = np.sqrt(mindsq) >>> pmin = np.min(x1,axis=0) >>> pmax = np.max(x1,axis=0) >>> >>> stats.append([m,x1,res,dt,mind,p1,p2,pmin,pmax]) >>> >>> logger.info("Minimum pair-wise distance in final configuration: {:8.4e}".format(mind)) >>> logger.info("First sample point in pair: ({:8.4e},{:8.4e},{:8.4e})".format(*p1)) >>> logger.info("Second sample point in pair ({:8.4e},{:8.4e},{:8.4e})".format(*p2)) >>> logger.info("Box lower boundary: ({:8.4e},{:8.4e},{:8.4e})".format(*box[0])) >>> logger.info("Minimum coordinates in sample: ({:8.4e},{:8.4e},{:8.4e})".format(*pmin)) >>> logger.info("Maximum coordinates in sample: ({:8.4e},{:8.4e},{:8.4e})".format(*pmax)) >>> logger.info("Box upper boundary: ({:8.4e},{:8.4e},{:8.4e})".format(*box[1])) >>> except: >>> logger.warn("{} failed.".format(m)) >>> continue >>> >>> stats_df = pd.DataFrame( [ { >>> 'method': s[0], >>> 'runtime': s[3], >>> 'mind': s[4], >>> **{'p1{:d}'.format(i): c for i,c in enumerate(s[5]) }, >>> **{'p2{:d}'.format(i): c for i,c in enumerate(s[6]) }, >>> **{'pmin{:d}'.format(i): c for i,c in enumerate(s[7]) }, >>> **{'pmax{:d}'.format(i): c for i,c in enumerate(s[8]) } >>> } for s in stats] ) >>> >>> print(stats_df.to_string(float_format='%8.6g')) method runtime mind p10 p11 p12 p20 p21 p22 pmin0 pmin1 pmin2 pmax0 pmax1 pmax2 0 initial 0 1.15674e-10 2.02188e-09 4.87564e-10 5.21835e-09 2.03505e-09 3.72691e-10 5.22171e-09 1.17135e-12 1.49124e-10 6.34126e-12 4.98407e-09 4.99037e-09 9.86069e-09 1 Powell 75.2704 8.02318e-10 4.23954e-09 3.36242e-09 8.80092e-09 4.31183e-09 2.56345e-09 8.81278e-09 4.01789e-10 4.0081e-10 4.2045e-10 4.59284e-09 4.54413e-09 9.5924e-09 2 CG 27.0756 7.9992e-10 3.39218e-09 4.00079e-09 8.27255e-09 3.86337e-09 4.27807e-09 7.68863e-09 4.00018e-10 4.00146e-10 4.00565e-10 4.59941e-09 4.59989e-09 9.59931e-09 3 BFGS 19.0255 7.99527e-10 1.82802e-09 3.54397e-09 9.69736e-10 2.41411e-09 3.936e-09 1.34664e-09 4.00514e-10 4.01874e-10 4.0002e-10 4.59695e-09 4.59998e-09 9.58155e-09 4 L-BFGS-B 11.7869 7.99675e-10 4.34395e-09 3.94096e-09 1.28996e-09 4.44064e-09 3.15999e-09 1.14778e-09 4.12146e-10 4.01506e-10 4.03583e-10 4.6e-09 4.59898e-09 9.5982e-09 """ import logging import time import numpy as np import scipy.optimize import scipy.spatial.distance from . import ffi # https://stackoverflow.com/questions/21377020/python-how-to-do-lazy-debug-logging class DeferredMessage(object): """Lazy evaluation for log messages.""" def __init__(self, msg, func, *args, **kwargs): self.msg = msg self.func = func self.args = args self.kwargs = kwargs def __str__(self): return self.msg.format(self.func(*self.args, **self.kwargs)) def brute_force_closest_pair(x): """Find coordinate pair with minimum distance squared ||xi-xj||^2. Parameters ---------- x: (N,dim) ndarray coordinates Returns ------- float, (ndarray, ndarray): minimum distance squared and coodinates pair Examples -------- Compare the performance of closest pair algorithms: >>> from matscipy.electrochemistry.steric_distribution import scipy_distance_based_target_function >>> from matscipy.electrochemistry.steric_distribution import numpy_only_target_function >>> from matscipy.electrochemistry.steric_distribution import brute_force_target_function >>> import itertools >>> import pandas as pd >>> import scipy.spatial.distance >>> import timeit >>> >>> funcs = [ >>> brute_force_closest_pair, >>> scipy_distance_based_closest_pair, >>> planar_closest_pair ] >>> func_names = ['brute','scipy','planar'] >>> stats = [] >>> N = 1000 >>> dim = 3 >>> for k in range(5): >>> x = np.random.rand(N,dim) >>> lambdas = [ (lambda x=x,f=f: f(x)) for f in funcs ] >>> rets = [ f() for f in lambdas ] >>> vals = [ v[0] for v in rets ] >>> coords = [ c for v in rets for p in v[1] for c in p ] >>> times = [ timeit.timeit(f,number=1) for f in lambdas ] >>> diffs = scipy.spatial.distance.pdist( >>> np.atleast_2d(vals).T,metric='euclidean') >>> stats.append((*vals,*diffs,*times,*coords)) >>> >>> func_name_tuples = list(itertools.combinations(func_names,2)) >>> diff_names = [ 'd_{:s}_{:s}'.format(f1,f2) for (f1,f2) in func_name_tuples ] >>> perf_names = [ 't_{:s}'.format(f) for f in func_names ] >>> coord_names = [ >>> 'p{:d}{:s}_{:s}'.format(i,a,f) for f in func_names for i in (1,2) for a in ('x','y','z') ] >>> float_fields = [*func_names,*diff_names,*perf_names,*coord_names] >>> dtypes = [ (field, 'f4') for field in float_fields ] >>> labeled_stats = np.array(stats,dtype=dtypes) >>> stats_df = pd.DataFrame(labeled_stats) >>> print(stats_df.T.to_string(float_format='%8.6g')) 0 1 2 3 4 brute 2.24089e-05 5.61002e-05 8.51047e-05 3.48424e-05 5.37235e-05 scipy 2.24089e-05 5.61002e-05 8.51047e-05 3.48424e-05 5.37235e-05 planar 2.24089e-05 5.61002e-05 8.51047e-05 3.48424e-05 5.37235e-05 d_brute_scipy 0 0 0 0 0 d_brute_planar 0 0 0 0 0 d_scipy_planar 0 0 0 0 0 t_brute 4.02697 3.85543 4.1414 3.90338 3.86993 t_scipy 0.00708364 0.00698962 0.00762594 0.00703242 0.00703579 t_planar 0.38302 0.39462 0.434342 0.407233 0.420773 p1x_brute 0.132014 0.331441 0.553405 0.534633 0.977582 p1y_brute 0.599688 0.186959 0.90897 0.575864 0.636278 p1z_brute 0.49631 0.993856 0.246418 0.853567 0.411793 p2x_brute 0.134631 0.333526 0.55322 0.534493 0.977561 p2y_brute 0.603598 0.179771 0.915063 0.576894 0.629313 p2z_brute 0.496833 0.994145 0.239493 0.859377 0.409509 p1x_scipy 0.132014 0.331441 0.553405 0.534633 0.977582 p1y_scipy 0.599688 0.186959 0.90897 0.575864 0.636278 p1z_scipy 0.49631 0.993856 0.246418 0.853567 0.411793 p2x_scipy 0.134631 0.333526 0.55322 0.534493 0.977561 p2y_scipy 0.603598 0.179771 0.915063 0.576894 0.629313 p2z_scipy 0.496833 0.994145 0.239493 0.859377 0.409509 p1x_planar 0.132014 0.331441 0.55322 0.534633 0.977561 p1y_planar 0.599688 0.186959 0.915063 0.575864 0.629313 p1z_planar 0.49631 0.993856 0.239493 0.853567 0.409509 p2x_planar 0.134631 0.333526 0.553405 0.534493 0.977582 p2y_planar 0.603598 0.179771 0.90897 0.576894 0.636278 p2z_planar 0.496833 0.994145 0.246418 0.859377 0.411793 """ logger = logging.getLogger(__name__) t0 = time.perf_counter() n = x.shape[0] imin = 0 jmin = 1 if n < 2: return (None, None), float('inf') dx = x[0,:] - x[1,:] dxsq = np.square(dx) mindsq = np.sum(dxsq) for i in np.arange(n): for j in np.arange(i+1, n): dx = x[i,:] - x[j,:] dxsq = np.square(dx) dxnormsq = np.sum(dxsq) if dxnormsq < mindsq: imin = i jmin = j mindsq = dxnormsq t1 = time.perf_counter()-t0 logger.debug("""Found minimum distance squared {:10.5e} for pair ({:d},{:d}) with coordinates {} and {} within {:10.5e} s.""".format( mindsq, imin, jmin, x[imin,:], x[jmin,:], t1)) return mindsq, (x[imin,:], x[jmin,:]) def recursive_closest_pair(x, y): """Find coordinate pair with minimum distance squared ||xi-xj||^2. Find coordinate pair with minimum distance squared ||xi-xj||^2 with one point from x and the other point from y Parameters ---------- x: (N,dim) ndarray coordinates Returns ------- float, (ndarray, ndarray): minimum distance squared and coordinate pair """ # t0 = time.perf_counter() n = x.shape[0] if n < 4: return brute_force_closest_pair(x) mid = n // 2 xl = x[:mid] xr = x[mid:] xdivider = x[mid,0] yl = [] yr = [] m = y.shape[0] for j in np.arange(m): if y[j,0] <= xdivider: yl.append(y[j,:]) else: yr.append(y[j,:]) yl = np.array(yl) yr = np.array(yr) mindsql, (pil, pjl) = recursive_closest_pair(xl, yl) mindsqr, (pir, pjr) = recursive_closest_pair(xr, yr) mindsq, (pim, pjm) = (mindsql, (pil, pjl)) if mindsql < mindsqr else ( mindsqr, (pir, pjr)) # TODO: this latter part only valid for 2d problems, # see https://sites.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf # some 3d implementation at # https://github.com/eyny/closest-pair-3d/blob/master/src/ballmanager.cpp close_y = np.array( [y[j,:] for j in np.arange(m) if (np.square(y[j,0]-xdivider) < mindsq)]) close_n = close_y.shape[0] if close_n > 1: for i in np.arange(close_n-1): for j in np.arange(i+1, min(i+8, close_n)): dx = close_y[i,:] - close_y[j,:] dxsq = np.square(dx) dxnormsq = np.sum(dxsq) if dxnormsq < mindsq: pim = close_y[i,:] pjm = close_y[j,:] mindsq = dxnormsq return mindsq, (pim, pjm) def planar_closest_pair(x): """Find coordinate pair with minimum distance ||xi-xj||. ATTENTION: this implementation tackles the planar problem! Parameters ---------- x: (N,dim) ndarray coordinates Returns ------- float, (ndarray, ndarray): minimum distance squared and coordinates pair """ logger = logging.getLogger(__name__) assert isinstance(x, np.ndarray), "np.ndarray expected for x" assert x.ndim == 2, "x is expected to be 2d array" t0 = time.perf_counter() I = np.argsort(x[:,0]) J = np.argsort(x[:,-1]) X = x[I,:] Y = x[J,:] mindsq, (pim, pjm) = recursive_closest_pair(X,Y) # mind = np.sqrt(mindsq) t1 = time.perf_counter()-t0 logger.debug("""Found minimum distance squared {:10.5e} for pair with coordinates {} and {} within {:10.5e} s.""".format(mindsq,pim,pjm,t1)) return mindsq, (pim, pjm) def scipy_distance_based_closest_pair(x): """Find coordinate pair with minimum distance ||xi-xj||. Parameters ---------- x: (N,dim) ndarray coordinates Returns ------- float, (ndarray, ndarray): minimum distance squared and coodinates pair Examples -------- Handling condensed distance matrix indices: >>> c = np.array([1, 2, 3, 4, 5, 6]) >>> print(c) [1 2 3 4 5 6] >>> d = scipy.spatial.distance.squareform(c) >>> print(d) [[0 1 2 3] [1 0 4 5] [2 4 0 6] [3 5 6 0]] >>> I,J = np.tril_indices(d.shape[0],-1) >>> print(I,J) [1 2 2 3 3 3] [0 0 1 0 1 2] >>> I,J = np.triu_indices(d.shape[0],1) >>> print(I,J) [0 0 0 1 1 2] [1 2 3 2 3 3] >>> print(d[I]) [1 2 4 3 5 6] """ logger = logging.getLogger(__name__) t0 = time.perf_counter() n = x.shape[0] dxnormsq = scipy.spatial.distance.pdist(x, metric='sqeuclidean') ij = np.argmin(dxnormsq) mindsq = dxnormsq[ij] # I,J = np.tril_indices(n,-1) I,J = np.triu_indices(n,1) imin,jmin = (I[ij],J[ij]) t1 = time.perf_counter()-t0 logger.debug("""Found minimum distance squared {:10.5e} for pair ({:d},{:d}) with coordinates {} and {} within {:10.5e} s.""".format( mindsq,imin,jmin,x[imin,:],x[jmin,:],t1)) return mindsq, (x[imin,:], x[jmin,:]) def brute_force_target_function(x, r=1.0, constraints=None): """Target function. Penalize dense packing for coordinates ||xi-xj||<ri+rj. Parameters ---------- x: (N,dim) ndarray particle coordinates r: float or (N,) ndarray, optional (default=1.0) steric radii of particles Returns ------- float: target function value Examples -------- Compare performance of target functions: >>> from matscipy.electrochemistry.steric_distribution import scipy_distance_based_target_function >>> from matscipy.electrochemistry.steric_distribution import numpy_only_target_function >>> from matscipy.electrochemistry.steric_distribution import brute_force_target_function >>> import itertools >>> import pandas as pd >>> import scipy.spatial.distance >>> import timeit >>> >>> funcs = [ >>> brute_force_target_function, >>> numpy_only_target_function, >>> scipy_distance_based_target_function ] >>> func_names = ['brute','numpy','scipy'] >>> >>> stats = [] >>> K = np.exp(np.log(10)*np.arange(-3,3)) >>> for k in K: >>> lambdas = [ (lambda x0=x0,k=k,f=f: f(x0*k)) for f in funcs ] >>> vals = [ f() for f in lambdas ] >>> times = [ timeit.timeit(f,number=1) for f in lambdas ] >>> diffs = scipy.spatial.distance.pdist(np.atleast_2d(vals).T,metric='euclidean') >>> stats.append((k,*vals,*diffs,*times)) >>> >>> func_name_tuples = list(itertools.combinations(func_names,2)) >>> diff_names = [ 'd_{:s}_{:s}'.format(f1,f2) for (f1,f2) in func_name_tuples ] >>> perf_names = [ 't_{:s}'.format(f) for f in func_names ] >>> fields = ['k',*func_names,*diff_names,*perf_names] >>> dtypes = [ (field, '>f4') for field in fields ] >>> labeled_stats = np.array(stats,dtype=dtypes) >>> stats_df = pd.DataFrame(labeled_stats) >>> print(stats_df.to_string(float_format='%8.6g')) k brute numpy scipy d_brute_numpy d_brute_scipy d_numpy_scipy t_brute t_numpy t_scipy 0 0.001 3.1984e+07 3.1984e+07 3.1984e+07 5.58794e-08 6.70552e-08 1.11759e-08 0.212432 0.168858 0.0734278 1 0.01 3.19829e+07 3.19829e+07 3.19829e+07 9.31323e-08 7.82311e-08 1.49012e-08 0.212263 0.16846 0.0791856 2 0.1 3.18763e+07 3.18763e+07 3.18763e+07 7.45058e-09 1.86265e-08 1.11759e-08 0.201706 0.164867 0.0711544 3 1 2.27418e+07 2.27418e+07 2.27418e+07 3.72529e-08 4.84288e-08 1.11759e-08 0.20762 0.166005 0.0724238 4 10 199751 199751 199751 1.16415e-10 2.91038e-11 8.73115e-11 0.202635 0.161932 0.0772684 5 100 252.548 252.548 252.548 3.28555e-11 0 3.28555e-11 0.202512 0.161217 0.0726705 """ logger = logging.getLogger(__name__) assert x.ndim == 2, "2d array expected for x" # sum_i sum_{j!=i} max(0,(r_i+r_j)"^2-||xi-xj||^2)^2 f = 0 n = x.shape[0] xi = x ri = r if not isinstance(r, np.ndarray) or r.shape != (n,): ri = ri*np.ones(n) assert ri.shape == (n,) zeros = np.zeros(n) for i in np.arange(1,n): rj = np.roll(ri, i, axis=0) xj = np.roll(xi, i, axis=0) d = ri + rj dsq = np.square(d) dx = xi - xj dxsq = np.square(dx) dxnormsq = np.sum(dxsq, axis=1) sqdiff = dsq - dxnormsq penalty = np.maximum(zeros, sqdiff) penaltysq = np.square(penalty) # half for double-counting f += 0.5*np.sum(penaltysq) if constraints: logger.debug( "Unconstrained penalty: {:10.5e}.".format(f)) f += constraints(x) logger.debug( "Total penalty: {:10.5e}.".format(f)) return f # TODO: code explicit Jacobian def scipy_distance_based_target_function(x, r=1.0, constraints=None): """Target function. Penalize dense packing for coordinates ||xi-xj||<ri+rj. Parameters ---------- x: (N,dim) ndarray particle coordinates r: float or (N,) ndarray, optional (default=1.0) steric radii of particles Returns ------- float: target function value """ logger = logging.getLogger(__name__) assert x.ndim == 2, "2d array expected for x" # sum_i sum_{j!=i} max(0,(r_i+r_j)"^2-||xi-xj||^2)^2 n = x.shape[0] if not isinstance(r, np.ndarray) or r.shape != (n,): r = r*np.ones(n) assert r.shape == (n,) # r(Nx1) kron ones(1xN) = Ri(NxN) Ri = np.kron(r, np.ones((n, 1))) Rj = Ri.T Dij = Ri + Rj dij = scipy.spatial.distance.squareform( Dij, force='tovector', checks=False) zeros = np.zeros(dij.shape) dsq = np.square(dij) dxnormsq = scipy.spatial.distance.pdist(x, metric='sqeuclidean') # computes the squared Euclidean distance ||u-v||_2^2 between vectors # https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html sqdiff = dsq - dxnormsq penalty = np.maximum(zeros, sqdiff) penaltysq = np.square(penalty) # no double-counting here f = np.sum(penaltysq) if constraints: logger.debug( "Unconstrained penalty: {:10.5e}.".format(f)) f += constraints(x) logger.debug( "Total penalty: {:10.5e}.".format(f)) return f # https://www.researchgate.net/publication/266617010_NumPy_SciPy_Recipes_for_Data_Science_Squared_Euclidean_Distance_Matrices def numpy_only_target_function(x, r=1.0, constraints=None): """Target function. Penalize dense packing for coordinates ||xi-xj||<ri+rj. Parameters ---------- x: (N,dim) ndarray particle coordinates r: float or (N,) ndarray, optional (default=1.0) steric radii of particles Returns ------- float: target function value """ logger = logging.getLogger(__name__) assert x.ndim == 2, "2d array expected for x" # sum_i sum_{j!=i} max(0,(r_i+r_j)"^2-||xi-xj||^2)^2 n = x.shape[0] if not isinstance(r, np.ndarray) or r.shape != (n,): r = r*np.ones(n) assert r.shape == (n,) zeros = np.zeros((n,n)) # r(Nx1) kron ones(1xN) = Ri(NxN) Ri = np.kron(r, np.ones((n,1))) Rj = Ri.T Dij = Ri + Rj dsq = np.square(Dij) np.fill_diagonal(dsq,0.) G = np.dot(x,x.T) H = np.tile(np.diag(G), (n,1)) dxnormsq = H + H.T - 2*G sqdiff = dsq - dxnormsq penalty = np.maximum(zeros, sqdiff) penaltysq = np.square(penalty) # half for double-counting f = 0.5*np.sum(penaltysq) if constraints: logger.debug( "Unconstrained penalty: {:10.5e}.".format(f)) f += constraints(x) logger.debug( "Total penalty: {:10.5e}.".format(f)) return f def neigh_list_based_target_function(x, r=1.0, constraints=None, Dij=None): """Target function. Penalize dense packing for coordinates ||xi-xj||<ri+rj. Parameters ---------- x: (N,dim) ndarray particle coordinates r: float or (N,) ndarray, optional (default=1.0) steric radii of particles constraints: callable, returns (float, (N,dim) ndarray) constraint function value and gradien Dij: (N, N) ndarray, optional (default=None) pairwise minimum allowed distance matrix, overrides r Returns ------- (float, (N,dim) ndarray): target function value and gradient f: float, target (or penalty) function, value evaluates to sum_i sum_{j!=i} max(0,(r_i+r_j)^2-||xi-xj||^2)^2 without double-counting pairs, where r_i and r_j are the steric radii of coordinate points i and j df: (N,dim) ndarray of float, the gradient, evaluates to 4*si sj ((r_i'+r_j)^2-||xi-xj||^2)^2)*(xik'-xjk')*(kdi'j-kdi'i) for entry (i',k'), where i subscribes the coordinate point and k the spatial dimension. kd is Kronecker delta, si is sum over i """ logger = logging.getLogger(__name__) # # function: # # f(x) = sum_i sum_{j!=i} max(0,(r_i+r_j)^2-||xi-xj||^2)^2 # # gradient: # # dfdxi'k'=4*si sj ((r_i'+r_j)^2-||xi-xj||^2)^2)*(xik'-xjk')*(kdi'j-kdi'i) # # for all pairs i'j within ri'+rj cutoff # where k is the spatial direction x, y or z. assert x.ndim == 2, "2d array expected for x" n = x.shape[0] if not Dij: if not isinstance(r, np.ndarray) or r.shape != (n,): r = r*np.ones(n) assert r.shape == (n,) # compute minimum allowed pairwise distances Dij (NxN matrix) # r(Nx1) kron ones(1xN) = Ri(NxN) Ri = np.kron(r, np.ones((n, 1))) Rj = Ri.T Dij = Ri + Rj # TODO: allow for periodic boundaries, for now use shrink wrapped box box = np.array([x.min(axis=0), x.max(axis=0)]) cell_origin = box[0,:] cell = np.diag(box[1,:] - box[0,:]) # get all pairs within their allowed minimum distance # parameters are # _matscipy.neighbour_list(quantities, cell_origin, cell, # np.linalg.inv(cell.T), pbc, positions, # cutoff, numbers) # If thhe parameter 'cutoff' is a per-atom value, then it must be a # diameter, not a radius (as wrongly stated within the function's # docstring) i, j, dxijnorm, dxijvec = ffi.neighbour_list( 'ijdD', cell_origin, cell, np.linalg.inv(cell.T), [0,0,0], x, 2.0*Ri, np.ones(len(x),dtype=np.int32)) # i, j are coordinate point indices, dxijnorm is pairwise distance, # dxvijvec is distance vector # nl contains redundancies, i.e. ij AND ji # pairs = list(zip(i,j)) logger.debug("Number of pairs within minimum allowed distance: {:d}" .format(len(i))) # get minimum allowed pairwise distance for all pairs within this distance dij = Dij[i,j] # (r_i'+r_j)^2 dsq = np.square(dij) # ||xi-xj||^2 dxnormsq = np.square(dxijnorm) # (r_i+r_j)^2-||xi-xj||^2 sqdiff = dsq - dxnormsq # ((r_i+r_j)^2-||xi-xj||^2)^2 penaltysq = np.square(sqdiff) # correct for double counting due to redundancies f = 0.5*np.sum(penaltysq) # 4*si sj ((r_i'+r_j)^2-||xi-xj||^2)^2)*(xik'-xjk')*(kdi'j-kdi'i) # (N x 1) column vector (a1 ... aN) * (N x dim) matrix ((d11,)) # Other than the formula above implicates, _matscipy.neighbour_list # returns the distance vector dxijvec = xj-xi (pointing from i to j), # thus positive sign in gradient below: gradij = 4*np.atleast_2d(sqdiff).T*dxijvec # let's hope for proper broadcasting grad = np.zeros(x.shape) grad[i] += gradij # Since neighbour list always includes ij and ji, we only have to treat i, # not j. The following line is obsolete (otherwise we would introduce # double-counting again): # grad[j] -= gradij if constraints: logger.debug( "Unconstrained penalty: {:10.5e}.".format(f)) logger.debug(DeferredMessage( "Unconstrained gradient norm: {:10.5e}.", np.linalg.norm, grad)) g, g_grad = constraints(x) f += g grad += g_grad grad_1d = grad.reshape(np.product(grad.shape)) logger.debug( "Total penalty: {:10.5e}.".format(f)) logger.debug(DeferredMessage( "Gradient norm: {:10.5e}.", np.linalg.norm, grad_1d)) return f, grad_1d def box_constraint(x, box=np.array([[0., 0., 0], [1.0, 1.0, 1.0]]), r=0.): """Constraint function. Confine coordinates within box. Parameters ---------- x: (N,dim) ndarray coordinates box: (2,dim) ndarray, optional (default: [[0.,0.,0.],[1.,1.,1.]]) box corner coordinates r: float or np.(N,) ndarray, optional (default=0) steric radii of particles Returns ------- float: penalty, positive """ logger = logging.getLogger(__name__) zeros = np.zeros(x.shape) r = np.atleast_2d(r).T # positive if coordinates out of box ldist = box[0, :] - x + r rdist = x + r - box[1, :] lpenalty = np.maximum(zeros, ldist) rpenalty = np.maximum(zeros, rdist) lpenaltysq = np.square(lpenalty) rpenaltysq = np.square(rpenalty) g = np.sum(lpenaltysq) + np.sum(rpenaltysq) logger.debug("Constraint penalty: {:.4g}.".format(g)) return g def box_constraint_with_gradient( x, box=np.array([[0., 0., 0], [1.0, 1.0, 1.0]]), r=0.): """Constraint function. Confine coordinates within box. Parameters ---------- x: (N,dim) ndarray coordinates box: (2,dim) ndarray, optional (default: [[0.,0.,0.],[1.,1.,1.]]) box corner coordinates r: float or np.(N,) ndarray, optional (default=0) steric radii of particles Returns ------- (float, (N,dim) ndarray of float): penalty g(x) and its gradient dg(x) g(x), positive: lik = box[0,k] - xik + ri > 0 for xik out of lower boundaries rik = xik + ri - box[1,k] > 0 for xik out of upper boundaries where box[0] and box[1] are lower and upper corner of bounding box and k marks spatial dimension. g(x) = sum_i sum_k ( max(0,lik) + max(0,rik) )^2 dg(x): gradient, entries accordingly evaluates to dgdxik(x) = 2*( -max(0,lik) + max(0,rik) ) """ logger = logging.getLogger(__name__) zeros = np.zeros(x.shape) r = np.atleast_2d(r).T # positive if coordinates out of box ldist = box[0, :] - x + r rdist = x + r - box[1, :] lpenalty = np.maximum(zeros, ldist) rpenalty = np.maximum(zeros, rdist) lpenaltysq = np.square(lpenalty) rpenaltysq = np.square(rpenalty) g = np.sum(lpenaltysq) + np.sum(rpenaltysq) logger.debug("Constraint penalty: {:.4g}.".format(g)) grad = -2*lpenalty + 2*rpenalty logger.debug(DeferredMessage( "Norm of constraint penalty gradient: {:.4g}.", np.linalg.norm, grad)) return g, grad def apply_steric_correction( x, box=None, r=None, method='L-BFGS-B', options={'gtol':1.e-8,'maxiter':100,'disp':True,'eps':1.0e-8}, target_function=neigh_list_based_target_function, returns_gradient=True, closest_pair_function=scipy_distance_based_closest_pair): """Enforce steric constraints on coordinate distribution within box. Parameters ---------- x : (N,dim) ndarray Particle coordinates. box: (2,dim) ndarray, optional (default: None) Box corner coordinates. r : float or (N,) ndarray, optional (default=None) Steric radius of particles. Can be specified particle-wise. options : dict, optional Forwarded to scipy minimzer. https://docs.scipy.org/doc/scipy/reference/optimize.minimize-bfgs.html (default: {'gtol':1.e-5,'maxiter':10,'disp':True,'eps':1.e-8}) target_function: func, optional One of the target functions within this submodule, or function of same signature. (default: neigh_list_based_target_function) returns_gradient: bool, optional (default: Trze) If True, then 'target_function' is expected to return a tuple (f, df) with f the actual target function value and df its (N,dim) gradient. This flag must be set for 'neigh_list_based_target_function'. closest_pair_function: func, optional One of the closest pair functions within this submodule, or function of same signature. (default: scipy_distance_based_closest_pair) Returns ------- float : (N,dim) ndarray Modified particle coordinates, meeting steric constraints. """ logger = logging.getLogger(__name__) assert isinstance(x, np.ndarray), "x must be np.ndarray" assert x.ndim == 2, "x must be 2d array" n = x.shape[0] dim = x.shape[1] if r is None: r = 0.0 logger.info("No steric radii explicitly specified, using none (zero).") r = np.atleast_1d(r) assert r.ndim == 1, "only isotropic steric radii r, no spatial dimensions" if r.shape[0] == 1: r = r*np.ones(n) assert r.shape[0] == n, "either one steric radius for all paricles or one each" if box is None: box = np.array(x.min(axis=0), x.max(axis=0)) logger.info("No bounding box explicitly specified, using extreme") logger.info("coordinates ({}) of coordinate set as default.".format( box)) assert isinstance(box, np.ndarray), "box must be np.ndarray" assert x.ndim == 2, "box must be 2d array" assert box.shape[0] == 2, "box must have two rows for outer corners" assert box.shape[1] == dim, "spatial dimensions of x and box must agree" V = np.product(box[1, :]-box[0, :]) L = np.power(V, (1./dim)) logger.info("Normalizing coordinates by reference length") logger.info(" L = V^(1/dim) = ({:.2g})^(1/{:d}) = {:.2g}.".format( V, dim, L)) # normalizing to unit volume necessary, # as target function apparently not dimension-insensitive BOX = box / L X0 = x / L R = r / L logger.info("Normalized bounding box: ") logger.info(" {}.".format(BOX[0])) logger.info(" {}.".format(BOX[1])) # flatten coordinates for scipy optimizer x0 = X0.reshape(np.product(X0.shape)) # define constraint and target wrapper for scipy optimizer if returns_gradient: def g(x): return box_constraint_with_gradient(x, box=BOX, r=R) def f(x): f, grad = target_function(x.reshape((n, dim)), r=R, constraints=g) return f, grad.reshape(np.product(grad.shape)) gval, ggrad = g(X0) fval, fgrad = f(x0) logger.info("Initial constraint penalty: {:10.5e}.".format(gval)) logger.info("Initial total penalty: {:10.5e}.".format(fval)) logger.info("Initial constraint gradient norm: {:10.5e}.".format( np.linalg.norm(ggrad))) logger.info("Initial total gradient norm: {:10.5e}.".format( np.linalg.norm(fgrad))) else: def g(x): return box_constraint(x, box=BOX, r=R) def f(x): return target_function(x.reshape((n, dim)), r=R, constraints=g) logger.info("Initial constraint penalty: {:10.5e}.".format(g(X0))) logger.info("Initial total penalty: {:10.5e}.".format(f(x0))) # log initial minimum distance between pairs minDsq, (P1, P2) = closest_pair_function(X0) # dimensionless mindsq, (p1, p2) = closest_pair_function(x) # dimensional minD = np.sqrt(minDsq) mind = np.sqrt(mindsq) # logger.info("Final distribution has residual penalty {:10.5e}.".format(f1)) logger.info("Min. dist. {:10.5e} between points".format(mind)) logger.info(" {} and".format(p1)) logger.info(" {}.".format(p2)) logger.info("Min. dist. {:10.5e} between dimensionless points".format(minD)) logger.info(" {} and".format(P1)) logger.info(" {}.".format(P2)) logger.info(" normalized by L = {:.2g}.".format(L)) def minimizer_callback(xk, *_): """Callback function to be used by optimizers of scipy.optimize. The second argument "*_" makes sure that it still works when the optimizer calls the callback function with more than one argument. See https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html """ nonlocal closest_pair_function, callback_count, tk, returns_gradient if callback_count == 0 and returns_gradient: logger.info( "{:>12s} {:>12s} {:>12s} {:>12s} {:>12s} {:>12s}".format( "#callback", "objective", "gradient", "min. dist.", "timing, step", "timing, tot.")) elif callback_count == 0: logger.info( "{:>12s} {:>12s} {:>12s} {:>12s} {:>12s}".format( "#callback", "objective", "min. dist.", "timing, step", "timing, tot.")) if returns_gradient: fk, gradk = f(xk) normgradk = np.linalg.norm(gradk) else: fk = f(xk) Xk = xk.reshape((n, dim)) mindsq, _ = closest_pair_function(Xk) mind = np.sqrt(mindsq) t1 = time.perf_counter() dt = t1 - tk dT = t1 - t0 tk = t1 if returns_gradient: logger.info( "{:12d} {:12.5e} {:12.5e} {:12.5e} {:12.5e} {:12.5e}".format( callback_count, fk, normgradk, mind, dt, dT)) else: logger.info( "{:12d} {:12.5e} {:12.5e} {:12.5e} {:12.5e}".format( callback_count, fk, mind, dt, dT)) callback_count += 1 callback_count = 0 t0 = time.perf_counter() tk = t0 # previosu callback timer value # call once for initial configuration if logger.isEnabledFor(logging.INFO): callback = minimizer_callback callback(x0) else: callback = None # neat lecture on scipy optimizers # http://scipy-lectures.org/advanced/mathematical_optimization/ res = scipy.optimize.minimize(f, x0, method=method, jac=returns_gradient, callback=callback, options=options) if not res.success: logger.warn(res.message) x1 = res.x # dimensionless, flat X1 = x1.reshape((n, dim)) # dimensionless, 2d if returns_gradient: gval, ggrad = g(X1) fval, fgrad = f(x1) logger.info("Final constraint penalty: {:10.5e}.".format(gval)) logger.info("Final total penalty: {:10.5e}.".format(fval)) logger.info("Final constraint gradient norm: {:10.5e}.".format( np.linalg.norm(ggrad))) logger.info("Final total gradient norm: {:10.5e}.".format( np.linalg.norm(fgrad))) else: logger.info("Final constraint penalty: {:10.5e}.".format(g(X1))) logger.info("Final total penalty: {:10.5e}.".format(f(x1))) x1 = X1*L # dimensional minDsq, (P1, P2) = closest_pair_function(X1) # dimensionless mindsq, (p1, p2) = closest_pair_function(x1) # dimensional minD = np.sqrt(minDsq) mind = np.sqrt(mindsq) # logger.info("Final distribution has residual penalty {:10.5e}.".format(f1)) logger.info("Min. dist. {:10.5e} between points".format(mind)) logger.info(" {} and".format(p1)) logger.info(" {}.".format(p2)) logger.info("Min. dist. {:10.5e} between dimensionless points".format(minD)) logger.info(" {} and".format(P1)) logger.info(" {}.".format(P2)) logger.info(" normalized by L = {:.2g}.".format(L)) dT = time.perf_counter() - t0 logger.info("Elapsed time: {:10.5} s.".format(dT)) return x1, res
39,585
35.417663
180
py
matscipy
matscipy-master/matscipy/electrochemistry/utility.py
# # Copyright 2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """ Electrochemistry module utility functions Copyright 2019, 2020 IMTEK Simulation University of Freiburg Authors: Johannes Hoermann <[email protected]> Lukas Elflein <[email protected]> """ import matplotlib.pyplot as plt def get_centers(bins): """Return the center of the provided bins. Example: >>> get_centers(bins=np.array([0.0, 1.0, 2.0])) array([ 0.5, 1.5]) """ bins = bins.astype(float) return (bins[:-1] + bins[1:]) / 2 def plot_dist(histogram, name, reference_distribution=None): """Plot histogram with an optional reference distribution.""" hist, bins = histogram width = 1 * (bins[1] - bins[0]) centers = get_centers(bins) fi, ax = plt.subplots() ax.bar( centers, hist, align='center', width=width, label='Empirical distribution', edgecolor="none") if reference_distribution is not None: ref = reference_distribution(centers) ref /= sum(ref) ax.plot(centers, ref, color='red', label='Target distribution') plt.title(name) plt.legend() plt.xlabel('Distance ' + name) plt.savefig(name + '.png')
1,955
29.5625
87
py
matscipy
matscipy-master/matscipy/electrochemistry/poisson_nernst_planck_solver.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """ Compute ion concentrations with general Poisson-Nernst-Planck (PNP) equations. Copyright 2019 IMTEK Simulation University of Freiburg Authors: Johannes Hoermann <[email protected]> """ import logging import time import numpy as np import scipy.constants as sc import scipy.optimize logger = logging.getLogger(__name__) # For the employed controlled volume scheme, we express the transport # equation's nonlinear part by the Bernoulli function # # $$ B(x) = \frac{x}{\exp(x)-1} $$ # # and use its Taylor expansion in the vicinity of zero for numeric stability. # Selbherr, S. Analysis and Simulation of Semiconductor Devices, Springer 1984 # employs a more complex piecewise definition, but for the stationary problem # our approach suffices. def B(x): """Bernoulli function.""" return np.where( np.abs(x) < 1e-9, 1 - x/2 + x**2/12 - x**4/720, # Taylor x / (np.exp(x) - 1)) # "lazy" Ansatz for approximating Jacobian def jacobian(f, x0, dx=np.NaN): """Naive way to construct N x N Jacobin Fij from N-valued function f of N-valued vector x0. Parameters ---------- f : callable N-valued function of N-valued variable vector x0 : (N,) ndarray N-valued variable vector dx : float (default: np.nan) Jacobian built with finite difference scheme of spacing ``dx``. If ``np.nan``, then use machine precision. Returns ------- F : (N,N) ndarray NxN-valued 2nd order finite difference scheme approximate of Jacobian convention: F_ij = dfidxj, where i are array rows, j are array columns """ N = len(x0) # choose step as small as possible if np.isnan(dx).any(): res = np.finfo('float64').resolution dx = np.abs(x0) * np.sqrt(res) dx[dx < res] = res if np.isscalar(dx): dx = np.ones(N) * dx F = np.zeros((N, N)) # Jacobian Fij # convention: dfi_dxj # i are rows, j are columns for j in range(N): dxj = np.zeros(N) dxj[j] = dx[j] F[:, j] = (f(x0 + dxj) - f(x0 - dxj)) / (2.0*dxj[j]) return F class PoissonNernstPlanckSystem: """Describes and solves a 1D Poisson-Nernst-Planck system""" # properties "offer" the solution in physical units: @property def grid(self): return self.X*self.l_unit @property def potential(self): return self.uij*self.u_unit @property def concentration(self): return np.where(self.nij > np.finfo('float64').resolution, self.nij*self.c_unit, 0.0) @property def charge_density(self): return np.sum(self.F * self.concentration.T * self.z, axis=1) @property def x1_scaled(self): return self.x0_scaled + self.L_scaled def newton(self, f, xij, **kwargs): """Newton solver expects system f and initial value xij Parameters ---------- f : callable N-valued function of N-valued vector xij : (N,) ndarray N-valued initial value vector Returns ------- xij : (N,) ndarray N-valued solution vector """ self.xij = [] self.converged = True # assume convergence, set to 'false' if maxit exceeded later self.logger.debug('Newton solver, grid points N = {:d}'.format(self.N)) self.logger.debug('Newton solver, tolerance e = {:> 8.4g}'.format(self.e)) self.logger.debug('Newton solver, maximum number of iterations M = {:d}'.format(self.maxit)) i = 0 delta_rel = 2*self.e self.logger.info("Convergence criterion: norm(dx) < {:4.2e}".format(self.e)) self.convergenceStepAbsolute = np.zeros(self.maxit) self.convergenceStepRelative = np.zeros(self.maxit) self.convergenceResidualAbsolute = np.zeros(self.maxit) dxij = np.zeros(self.N) while delta_rel > self.e and i < self.maxit: self.logger.debug('*** Newton solver iteration {:d} ***'.format(i)) # avoid cluttering log self.logger.disabled = True J = jacobian(f, xij) self.logger.disabled = False rank = np.linalg.matrix_rank(J) self.logger.debug(' Jacobian ({}) rank {:d}'.format(J.shape, rank)) if rank < self.N: self.logger.warn("Singular jacobian of rank {:d} < {:d} at step {:d}".format(rank, self.N, i)) break F = f(xij) invJ = np.linalg.inv(J) dxij = np.dot(invJ, F) delta = np.linalg.norm(dxij) delta_rel = delta / np.linalg.norm(xij) xij -= dxij self.xij.append(xij) normF = np.linalg.norm(F) self.logger.debug(' convergence norm(dxij), absolute {:> 8.4g}'.format(delta)) self.logger.debug(' convergence norm(dxij), relative {:> 8.4g}'.format(delta_rel)) self.logger.debug(' residual norm(F), absolute {:> 8.4g}'.format(normF)) self.convergenceStepAbsolute[i] = delta self.convergenceStepRelative[i] = delta_rel self.convergenceResidualAbsolute[i] = normF self.logger.info("Step {:4d}: norm(dx)/norm(x) = {:4.2e}, norm(dx) = {:4.2e}, norm(F) = {:4.2e}".format( i, delta_rel, delta, normF)) i += 1 if i == self.maxit: self.logger.warn("Maximum number of iterations reached") self.converged = False self.logger.info("Ended after {:d} steps.".format(i)) self.convergenceStepAbsolute = self.convergenceStepAbsolute[:i] self.convergenceStepRelative = self.convergenceStepRelative[:i] self.convergenceResidualAbsolute = self.convergenceResidualAbsolute[:i] return xij def solver_callback(self, xij, *_): """Callback function that can be used by optimizers of scipy.optimize. The second argument "*_" makes sure that it still works when the optimizer calls the callback function with more than one argument. See https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html """ if self.callback_count == 0: logger.info( "{:>12s} {:>12s} {:>12s} {:>12s} {:>12s} {:>12s}".format( "#callback", "residual norm", "abs dx norm", "rel dx norm", "timing, step", "timing, tot.")) self.xij = [self.xi0] self.converged = True # TODO remove (?) self.convergenceStepAbsolute = [] self.convergenceStepRelative = [] self.convergenceResidualAbsolute = [] dxij = np.zeros(self.N) self.xij.append(xij) dxij = xij - self.xij[self.callback_count] delta = np.linalg.norm(dxij) delta_rel = delta / np.linalg.norm(xij) fj = self.G(xij) norm_fj = np.linalg.norm(fj) self.convergenceStepAbsolute.append(delta) self.convergenceStepRelative.append(delta_rel) self.convergenceResidualAbsolute.append(norm_fj) t1 = time.perf_counter() dt = t1 - self.tj dT = t1 - self.t0 self.tj = t1 logger.info( "{:12d} {:12.5e} {:12.5e} {:12.5e} {:12.5e} {:12.5e}".format( self.callback_count, norm_fj, delta, delta_rel, dt, dT)) self.callback_count += 1 return def discretize(self): """Sets up discretization scheme and initial value""" # indices self.Ni = self.N+1 I = np.arange(self.Ni) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'discretization segments N', self.N, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'grid points N', self.Ni, lwidth=self.label_width)) # discretization self.dx = self.L_scaled / self.N # spatial step self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'dx', self.dx, lwidth=self.label_width)) # positions (scaled) self.X = self.x0_scaled + I*self.dx # Boundary & initial values # internally: # n: dimensionless concentrations # u: dimensionless potential # i: spatial index # j: temporal index # k: species index # initial concentrations equal to bulk concentrations # Kronecker product, M rows (ion species), Ni cols (grid points), if self.ni0 is None: self.ni0 = np.kron(self.c_scaled, np.ones((self.Ni, 1))).T if self.zi0 is None: self.zi0 = np.kron(self.z, np.ones((self.Ni, 1))).T # does not change # self.initial_values() def initial_values(self): """ Solves decoupled linear system to get initial potential distribution. """ zini0 = self.zi0*self.ni0 # z*n # shape: ion species (rows), grid points (cols), sum over ion species (along rows) rhoi0 = 0.5*zini0.sum(axis=0) # system matrix of spatial poisson equation Au = np.zeros((self.Ni, self.Ni)) bu = np.zeros(self.Ni) Au[0, 0] = 1 Au[-1, -1] = 1 for i in range(1, self.N): Au[i, [i-1, i, i+1]] = [1.0, -2.0, 1.0] # 1D Laplace operator, 2nd order bu = rhoi0*self.dx**2 # => Poisson equation bu[0] = self.u0 bu[-1] = self.u1 # get initial potential distribution by solving Poisson equation self.ui0 = np.dot(np.linalg.inv(Au), bu) # A u - b = 0 <=> u = A^-1 b return self.ui0 # evokes Newton solver def solve(self): """Evokes solver Returns ------- uij : (Ni,) ndarray potential at Ni grid points nij : (M,Nij) ndarray concentrations of M species at Ni grid points lamj: (L,) ndarray value of L Lagrange multipliers (not implemented, empty) """ # if not yet done, set up initial values if self.ui0 is None: self.initial_values() if len(self.g) > 0: self.xi0 = np.concatenate([self.ui0, self.ni0.flatten(), np.zeros(len(self.g))]) else: self.xi0 = np.concatenate([self.ui0, self.ni0.flatten()]) self.callback_count = 0 self.t0 = time.perf_counter() self.tj = self.t0 # previous callback timer value # neat lecture on scipy optimizers # http://scipy-lectures.org/advanced/mathematical_optimization/ if isinstance(self.solver, str) and self.solver in [ 'hybr', 'lm', 'broyden1', 'broyden2', 'anderson', 'linearmixing', 'diagbroyden', 'excitingmixing', 'krylov', 'df-sane']: res = scipy.optimize.root(self.G, self.xi0, method=self.solver, callback=self.solver_callback, options=self.options) self.xij1 = res.x if not res.success: logger.warn(res.message) elif isinstance(self.solver, str): f = lambda x: np.linalg.norm(self.G(x)) res = scipy.optimize.minimize(f, self.xi0.copy(), method=self.solver, callback=self.solver_callback, options=self.options) self.xij1 = res.x if not res.success: logger.warn(res.message) else: self.xij1 = self.solver(self.G, self.xi0.copy(), callback=self.solver_callback, options=self.options) # store results: self.uij = self.xij1[:self.Ni] # potential self.nij = self.xij1[self.Ni:(self.M+1)*self.Ni].reshape(self.M, self.Ni) # concentrations self.lamj = self.xij1[(self.M+1)*self.Ni:] # Lagrange multipliers return self.uij, self.nij, self.lamj # standard sets of boundary conditions: def useStandardInterfaceBC(self): """Interface at left hand side and open bulk at right hand side""" self.boundary_conditions = [] # Potential Dirichlet BC self.u0 = self.delta_u_scaled self.u1 = 0 self.logger.info( 'Left hand side Dirichlet boundary condition: u0 = {:> 8.4g}'.format(self.u0)) self.logger.info( 'Right hand side Dirichlet boundary condition: u1 = {:> 8.4g}'.format(self.u1)) self.boundary_conditions.extend([ lambda x: self.leftPotentialDirichletBC(x, self.u0), lambda x: self.rightPotentialDirichletBC(x, self.u1)]) for k in range(self.M): self.logger.info( 'Ion species {:02d} left hand side concentration Flux boundary condition: j0 = {:> 8.4g}'.format( k,0)) self.logger.info( 'Ion species {:02d} right hand side concentration Dirichlet boundary condition: c1 = {:> 8.4g}'.format( k, self.c_scaled[k])) self.boundary_conditions.extend([ lambda x, k=k: self.leftControlledVolumeSchemeFluxBC(x, k), lambda x, k=k: self.rightDirichletBC(x, k, self.c_scaled[k])]) # counter-intuitive behavior of lambda in loop: # https://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture # workaround: default parameter k=k def useStandardCellBC(self): """Interfaces at left hand side and right hand side""" self.boundary_conditions = [] # Potential Dirichlet BC self.u0 = self.delta_u_scaled / 2.0 self.u1 = - self.delta_u_scaled / 2. self.logger.info('{:>{lwidth}s} u0 = {:< 8.4g}'.format( 'Left hand side Dirichlet boundary condition', self.u0, lwidth=self.label_width)) self.logger.info('{:>{lwidth}s} u1 = {:< 8.4g}'.format( 'Right hand side Dirichlet boundary condition', self.u1, lwidth=self.label_width)) self.boundary_conditions.extend([ lambda x: self.leftPotentialDirichletBC(x, self.u0), lambda x: self.rightPotentialDirichletBC(x, self.u1)]) N0 = self.L_scaled*self.c_scaled # total amount of species in cell for k in range(self.M): self.logger.info('{:>{lwidth}s} j0 = {:<8.4g}'.format( 'Ion species {:02d} left hand side concentration Flux boundary condition'.format(k), 0.0, lwidth=self.label_width)) self.logger.info('{:>{lwidth}s} N0 = {:<8.4g}'.format( 'Ion species {:02d} number conservation constraint'.format(k), N0[k], lwidth=self.label_width)) self.boundary_conditions.extend([ lambda x, k=k: self.leftControlledVolumeSchemeFluxBC(x, k), lambda x, k=k, N0=N0[k]: self.numberConservationConstraint(x, k, N0)]) def useSternLayerCellBC(self, implicit=False): """Interfaces at left hand side and right hand side, Stern layer either by prescribing linear potential regime between cell boundary and outer Helmholtz plane (OHP), or by applying Robin BC; zero flux BC on all ion species. Parameters ---------- implicit : bool, optional If true, then true Robin BC are applied. Attention: if desired, domain must be cropped by manually by twice the Stern layer thickness lambda_S. Otherwise, enforces constant potential gradient across Stern layer region of thickness lambda_S. (default:False) """ self.boundary_conditions = [] # Potential Dirichlet BC self.u0 = self.delta_u_scaled / 2.0 self.u1 = - self.delta_u_scaled / 2.0 if implicit: # implicitly treat Stern layer via Robin BC self.logger.info('Implicitly treating Stern layer via Robin BC') self.logger.info('{:>{lwidth}s} u0 + lambda_S*dudx = {:< 8.4g}'.format( 'Left hand side Robin boundary condition', self.u0, lwidth=self.label_width)) self.logger.info('{:>{lwidth}s} u1 + lambda_S*dudx = {:< 8.4g}'.format( 'Right hand side Robin boundary condition', self.u1, lwidth=self.label_width)) self.boundary_conditions.extend([ lambda x: self.leftPotentialRobinBC(x, self.lambda_S_scaled, self.u0), lambda x: self.rightPotentialRobinBC(x, self.lambda_S_scaled, self.u1)]) else: # explicitly treat Stern layer via linear regime self.logger.info('Explicitly treating Stern layer as uniformly charged regions') # set left and right hand side outer Helmholtz plane self.lhs_ohp = self.x0_scaled + self.lambda_S_scaled self.rhs_ohp = self.x0_scaled + self.L_scaled - self.lambda_S_scaled self.logger.info('{:>{lwidth}s} u0 = {:< 8.4g}'.format( 'Left hand side Dirichlet boundary condition', self.u0, lwidth=self.label_width)) self.logger.info('{:>{lwidth}s} u1 = {:< 8.4g}'.format( 'Right hand side Dirichlet boundary condition', self.u1, lwidth=self.label_width)) self.boundary_conditions.extend([ lambda x: self.leftPotentialDirichletBC(x, self.u0), lambda x: self.rightPotentialDirichletBC(x, self.u1)]) N0 = self.L_scaled*self.c_scaled # total amount of species in cell for k in range(self.M): self.logger.info('{:>{lwidth}s} j0 = {:<8.4g}'.format( 'Ion species {:02d} left hand side concentration Flux boundary condition'.format(k), 0.0, lwidth=self.label_width)) self.logger.info('{:>{lwidth}s} N0 = {:<8.4g}'.format( 'Ion species {:02d} number conservation constraint'.format(k), N0[k], lwidth=self.label_width)) self.boundary_conditions.extend([ lambda x, k=k: self.leftControlledVolumeSchemeFluxBC(x, k), lambda x, k=k, N0=N0[k]: self.numberConservationConstraint(x, k, N0)]) # TODO: meaningful test for Dirichlet BC def useStandardDirichletBC(self): """Dirichlet BC for all variables at all boundaries""" self.boundary_conditions = [] self.u0 = self.delta_u_scaled self.u1 = 0 self.logger.info( 'Left hand side potential Dirichlet boundary condition: u0 = {:> 8.4g}'.format(self.u0)) self.logger.info( 'Right hand side potential Dirichlet boundary condition: u1 = {:> 8.4g}'.format(self.u1)) # set up boundary conditions self.boundary_conditions.extend([ lambda x: self.leftPotentialDirichletBC(x, self.u0), lambda x: self.rightPotentialDirichletBC(x, self.u1)]) for k in range(self.M): self.logger.info( 'Ion species {:02d} left hand side concentration Dirichlet boundary condition: c0 = {:> 8.4g}'.format( k, self.c_scaled[k])) self.logger.info( 'Ion species {:02d} right hand side concentration Dirichlet boundary condition: c1 = {:> 8.4g}'.format( k, self.c_scaled[k])) self.boundary_conditions.extend([ lambda x, k=k: self.leftDirichletBC(x, k, self.c_scaled[k]), lambda x, k=k: self.rightDirichletBC(x, k, self.c_scaled[k])]) # boundary conditions and constraints building blocks: def leftFiniteDifferenceSchemeFluxBC(self, x, k, j0=0): """ Parameters ---------- x : (Ni,) ndarray N-valued variable vector k : int ion species (-1 for potential) j0 : float flux of ion species `k` at left hand boundary Returns ------- float: boundary condition residual """ uij = x[:self.Ni] nijk = x[(k+1)*self.Ni:(k+2)*self.Ni] # 2nd order right hand side finite difference scheme: # df0dx = 1 / (2*dx) * (-3 f0 + 4 f1 - f2 ) + O(dx^2) # - dndx - z n dudx = j0 dndx = -3.0*nijk[0] + 4.0*nijk[1] - nijk[2] dudx = -3.0*uij[0] + 4.0*uij[1] - uij[2] bcval = - dndx - self.zi0[k, 0]*nijk[0]*dudx - 2.0*self.dx*j0 self.logger.debug( 'Flux BC F[0] = - dndx - z n dudx - 2*dx*j0 = {:> 8.4g}'.format(bcval)) self.logger.debug( ' = - ({:.2f}) - ({:.0f})*{:.2f}*({:.2f}) - 2*{:.2f}*({:.2f})'.format( dndx, self.zi0[k, 0], nijk[0], dudx, self.dx, j0)) return bcval def rightFiniteDifferenceSchemeFluxBC(self, x, k, j0=0): """ See ```leftFiniteDifferenceSchemeFluxBC``` """ uij = x[:self.Ni] nijk = x[(k+1)*self.Ni:(k+2)*self.Ni] # 2nd order left hand side finite difference scheme: # df0dx = 1 / (2*dx) * (-3 f0 + 4 f1 - f2 ) + O(dx^2) # - dndx - z n dudx = j0 dndx = 3.0*nijk[-1] - 4.0*nijk[-2] + nijk[-3] dudx = 3.0*uij[-1] - 4.0*uij[-2] + uij[-3] bcval = - dndx - self.zi0[k, -1]*nijk[-1]*dudx - 2.0*self.dx*j0 self.logger.debug( 'FD flux BC F[-1] = - dndx - z n dudx - 2*dx*j0 = {:> 8.4g}'.format(bcval)) self.logger.debug( ' = - {:.2f} - {:.0f}*{:.2f}*{:.2f} - 2*{:.2f}*{:.2f}'.format( dndx, self.zi0[k, -1], nijk[-1], dudx, self.dx, j0)) return bcval def leftControlledVolumeSchemeFluxBC(self, x, k, j0=0): """ Compute left hand side flux boundary condition residual in accord with controlled volume scheme. Parameters ---------- x : (Ni,) ndarray N-valued variable vector k : int ion species (-1 for potential) j0 : float flux of ion species `k` at left hand boundary Returns ------- float: boundary condition residual """ uij = x[:self.Ni] nijk = x[(k+1)*self.Ni:(k+2)*self.Ni] # flux by controlled volume scheme: bcval = (+ B(self.z[k]*(uij[0]-uij[1]))*nijk[1] - B(self.z[k]*(uij[1]-uij[0]))*nijk[0] - self.dx*j0) self.logger.debug( 'CV flux BC F[0] = n1*B(z(u0-u1)) - n0*B(z(u1-u0)) - j0*dx = {:> 8.4g}'.format(bcval)) return bcval def rightControlledVolumeSchemeFluxBC(self, x, k, j0=0): """ Compute right hand side flux boundary condition residual in accord with controlled volume scheme. See ``leftControlledVolumeSchemeFluxBC`` """ uij = x[:self.Ni] nijk = x[(k+1)*self.Ni:(k+2)*self.Ni] # flux by controlled volume scheme: bcval = (+ B(self.z[k]*(uij[-2]-uij[-1]))*nijk[-1] - B(self.z[k]*(uij[-1]-uij[-2]))*nijk[-2] - self.dx*j0) self.logger.debug( 'CV flux BC F[-1] = n[-1]*B(z(u[-2]-u[-1])) - n[-2]*B(z(u[-1]-u[-2])) - j0*dx = {:> 8.4g}'.format(bcval)) return bcval def leftPotentialDirichletBC(self, x, u0=0): return self.leftDirichletBC(x, -1, u0) def leftDirichletBC(self, x, k, x0=0): """Construct Dirichlet BC at left boundary""" nijk = x[(k+1)*self.Ni:(k+2)*self.Ni] return nijk[0] - x0 def rightPotentialDirichletBC(self, x, x0=0): return self.rightDirichletBC(x, -1, x0) def rightDirichletBC(self, x, k, x0=0): nijk = x[(k+1)*self.Ni:(k+2)*self.Ni] return nijk[-1] - x0 def leftPotentialRobinBC(self, x, lam, u0=0): return self.leftRobinBC(x, -1, lam, u0) def leftRobinBC(self, x, k, lam, x0=0): """ Compute left hand side Robin (u + lam*dudx = u0 ) BC at in accord with 2nd order finite difference scheme. Parameters ---------- x : (Ni,) ndarray N-valued variable vector k : int ion species (-1 for potential) lam: float BC coefficient, corresponds to Stern layer thickness if applied to potential variable in PNP problem. Here, this steric layer is assumed to constitute a region of uniform charge density and thus linear potential drop across the interface. x0 : float right hand side value of BC, corresponds to potential beyond Stern layer if applied to potential variable in PNP system. Returns ------- float: boundary condition residual """ nijk = x[(k+1)*self.Ni:(k+2)*self.Ni] return nijk[0] + lam/(2*self.dx) * (3.0*nijk[0] - 4.0*nijk[1] + nijk[2]) - x0 def rightPotentialRobinBC(self, x, lam, u0=0): return self.rightRobinBC(x, -1, lam, u0) def rightRobinBC(self, x, k, lam, x0=0): """Construct Robin (u + lam*dudx = u0 ) BC at right boundary.""" nijk = x[(k+1)*self.Ni:(k+2)*self.Ni] return nijk[-1] + lam/(2*self.dx) * (3.0*nijk[-1] - 4.0*nijk[-2] + nijk[-3]) - x0 def numberConservationConstraint(self, x, k, N0): """N0: total amount of species, k: ion species""" nijk = x[(k+1)*self.Ni:(k+2)*self.Ni] ## TODO: this integration scheme assumes constant concentrations within ## an interval. Adapt to controlled volume scheme! # rescale to fit interval N = np.sum(nijk*self.dx) * self.N / self.Ni constraint_val = N - N0 self.logger.debug( 'Number conservation constraint F(x) = N - N0 = {:.4g} - {:.4g} = {:.4g}'.format( N, N0, constraint_val)) return constraint_val # TODO: remove or standardize # def leftNeumannBC(self,x,j0): # """Construct finite difference Neumann BC (flux BC) at left boundary""" # # right hand side first derivative of second order error # # df0dx = 1 / (2*dx) * (-3 f0 + 4 f1 - f2 ) + O(dx^2) = j0 # bcval = -3.0*x[0] + 4.0*x[1] - x[2] - 2.0*self.dx*j0 # self.logger.debug( # 'Neumann BC F[0] = -3*x[0] + 4*x[1] - x[2] = {:> 8.4g}'.format(bcval)) # return bcval # # def rightNeumannBC(self,x,j0): # """Construct finite difference Neumann BC (flux BC) at right boundary""" # # left hand side first derivative of second order error # # dfndx = 1 / (2*dx) * (+3 fn - 4 fn-1 + fn-2 ) + O(dx^2) = 0 # bcval = 3.0*x[-1] - 4.0*x[-2] + x[-3] - 2.0*self.dx*j0 # self.logger.debug( # 'Neumann BC F[-1] = -3*x[-1] + 4*x[-2] - nijk[-3] = {:> 8.4g}'.format(bcval)) # return bcval # standard Poisson equation residual for potential def poisson_pde(self, x): """Returns Poisson equation residual by applying 2nd order FD scheme""" uij1 = x[:self.Ni] self.logger.debug( 'potential range [u_min, u_max] = [ {:>.4g}, {:>.4g} ]'.format( np.min(uij1), np.max(uij1))) nij1 = x[self.Ni:(self.M+1)*self.Ni] nijk1 = nij1.reshape(self.M, self.Ni) for k in range(self.M): self.logger.debug( 'ion species {:02d} concentration range [c_min, c_max] = [ {:>.4g}, {:>.4g} ]'.format( k, np.min(nijk1[k, :]), np.max(nijk1[k, :]))) # M rows (ion species), N_i cols (grid points) zi0nijk1 = self.zi0*nijk1 # z_ik*n_ijk for k in range(self.M): self.logger.debug( 'ion species {:02d} charge range [z*c_min, z*c_max] = [ {:>.4g}, {:>.4g} ]'.format( k, np.min(zi0nijk1[k, :]), np.max(zi0nijk1[k, :]))) # charge density sum_k=1^M (z_ik*n_ijk) rhoij1 = zi0nijk1.sum(axis=0) self.logger.debug( 'charge density range [rho_min, rho_max] = [ {:>.4g}, {:>.4g} ]'.format( np.min(rhoij1), np.max(rhoij1))) # reduced Poisson equation: d2udx2 = rho Fu = -(np.roll(uij1, -1)-2*uij1+np.roll(uij1, 1))-0.5*rhoij1*self.dx**2 # linear potential regime due to steric effects incorporated here # TODO: incorporate "spatially finite" BC into Robin BC functions # replace left and right hand side residuals with linear potential FD if not np.isnan(self.lhs_ohp): lhs_linear_regime_ndx = (self.X <= self.lhs_ohp) lhs_ohp_ndx = np.max(np.nonzero(lhs_linear_regime_ndx)) self.logger.debug( 'selected {:d} grid points within lhs OHP at grid point index {:d} with x_scaled <= {:>.4g}'.format( np.count_nonzero(lhs_linear_regime_ndx), lhs_ohp_ndx, self.lhs_ohp)) # dudx = (u[ohp]-u[0])/lambda_S within Stern layer Fu[lhs_linear_regime_ndx] = ( (np.roll(uij1, -1) - uij1)[lhs_linear_regime_ndx] * self.lambda_S_scaled - (uij1[lhs_ohp_ndx]-uij1[0])*self.dx) if not np.isnan(self.rhs_ohp): rhs_linear_regime_ndx = (self.X >= self.rhs_ohp) rhs_ohp_ndx = np.min(np.nonzero(rhs_linear_regime_ndx)) self.logger.debug( 'selected {:d} grid points within lhs OHP at grid point index {:d} with x_scaled >= {:>.4g}'.format( np.count_nonzero(rhs_linear_regime_ndx), rhs_ohp_ndx, self.rhs_ohp)) # dudx = (u[ohp]-u[0])/lambda_S within Stern layer Fu[rhs_linear_regime_ndx] = ( (uij1 - np.roll(uij1, 1))[rhs_linear_regime_ndx] * self.lambda_S_scaled - (uij1[-1]-uij1[rhs_ohp_ndx])*self.dx) Fu[0] = self.boundary_conditions[0](x) Fu[-1] = self.boundary_conditions[1](x) self.logger.debug('Potential BC residual Fu[0] = {:> 8.4g}'.format(Fu[0])) self.logger.debug('Potential BC residual Fu[-1] = {:> 8.4g}'.format(Fu[-1])) return Fu def nernst_planck_pde(self, x): """Returns Nernst-Planck equation residual by applying controlled volume scheme""" uij1 = x[:self.Ni] self.logger.debug( 'potential range [u_min, u_max] = [ {:>.4g}, {:>.4g} ]'.format( np.min(uij1), np.max(uij1))) nij1 = x[self.Ni:(self.M+1)*self.Ni] nijk1 = nij1.reshape(self.M, self.Ni) for k in range(self.M): self.logger.debug( 'ion species {:02d} concentration range [c_min, c_max] = [ {:>.4g}, {:>.4g} ]'.format( k, np.min(nijk1[k, :]), np.max(nijk1[k, :]))) Fn = np.zeros([self.M, self.Ni]) # loop over k = 1..M reduced Nernst-Planck equations: # - d2nkdx2 - ddx (zk nk dudx ) = 0 for k in range(self.M): # controlled volume implementation: constant flux across domain Fn[k, :] = ( + B(self.zi0[k, :]*(uij1 - np.roll(uij1, -1))) * np.roll(nijk1[k, :], -1) - B(self.zi0[k, :]*(np.roll(uij1, -1) - uij1)) * nijk1[k, :] - B(self.zi0[k, :]*(np.roll(uij1, +1) - uij1)) * nijk1[k, :] + B(self.zi0[k, :]*(uij1 - np.roll(uij1, +1))) * np.roll(nijk1[k, :], +1)) Fn[k, 0] = self.boundary_conditions[2*k+2](x) Fn[k, -1] = self.boundary_conditions[2*k+3](x) self.logger.debug( 'ion species {k:02d} BC residual Fn[{k:d},0] = {:> 8.4g}'.format( Fn[k, 0], k=k)) self.logger.debug( 'ion species {k:02d} BC residual Fn[{k:d},-1] = {:> 8.4g}'.format( Fn[k, -1], k=k)) return Fn # non-linear system, "controlled volume" method # Selbherr, S. Analysis and Simulation of Semiconductor Devices, Springer 1984 def G(self, x): """Non-linear system Discretization of Poisson-Nernst-Planck system with M ion species. Implements "controlled volume" method as found in Selbherr, Analysis and Simulation of Semiconductor Devices, Springer 1984 Parameters ---------- x : ((M+1)*Ni,) ndarray system variables. 1D array of (M+1)*Ni values, where M is number of ion species, Ni number of spatial discretization points. First Ni entries are expected to contain potential, following M*Ni points contain ion concentrations. Returns -------- residual: ((M+1)*Ni,) ndarray """ # reduced Poisson equation: d2udx2 = rho Fu = self.potential_pde(x) Fn = self.concentration_pde(x) # Apply constraints if set (not implemented properly, do not use): if len(self.g) > 0: Flam = np.array([g(x) for g in self.g]) F = np.concatenate([Fu, Fn.flatten(), Flam]) else: F = np.concatenate([Fu, Fn.flatten()]) return F @property def I(self): # ionic strength """Compute the system's ionic strength from charges and concentrations. Returns ------- I : float ionic strength ( 1/2 * sum(z_i^2*c_i) ) [concentration unit, i.e. mol m^-3] """ return 0.5*np.sum(np.square(self.z) * self.c) @property def lambda_D(self): """Compute the system's Debye length. Returns ------- lambda_D : float Debye length, sqrt( epsR*eps*R*T/(2*F^2*I) ) [length unit, i.e. m] """ return np.sqrt( self.relative_permittivity*self.vacuum_permittivity*self.R*self.T/( 2.0*self.F**2*self.I)) # default 0.1 mM (i.e. mol/m^3) NaCl aqueous solution def init(self, c=np.array([0.1, 0.1]), z=np.array([1, -1]), L=100e-9, # 100 nm lambda_S=0, # Stern layer (compact layer) thickness x0=0, # zero position T=298.15, delta_u=0.05, # potential difference [V] relative_permittivity=79, vacuum_permittivity=sc.epsilon_0, R=sc.value('molar gas constant'), F=sc.value('Faraday constant'), N=200, # number of grid segments, number of grid points Ni = N + 1 e=1e-10, # absolute tolerance, TODO: switch to standardized measure maxit=20, # maximum number of Newton iterations solver=None, options=None, potential0=None, concentration0=None): """Initializes a 1D Poisson-Nernst-Planck system description. Expects quantities in SI units per default. Parameters ---------- c : (M,) ndarray, optional bulk concentrations of each ionic species [mol/m^3] (default: [ 0.1, 0.1 ]) z : (M,) ndarray, optional charge of each ionic species [1] (default: [ +1, -1 ]) x0 : float, optional left hand side reference position (default: 0) L : float, optional 1D domain size [m] (default: 100e-9) lambda_S: float, optional Stern layer thickness in case of Robin BC [m] (default: 0) T : float, optional temperature of the solution [K] (default: 298.15) delta_u : float, optional potential drop across 1D cell [V] (default: 0.05) relative_permittivity: float, optional relative permittivity of the ionic solution [1] (default: 79) vacuum_permittivity: float, optional vacuum permittivity [F m^-1] (default: 8.854187817620389e-12 ) R : float, optional molar gas constant [J mol^-1 K^-1] (default: 8.3144598) F : float, optional Faraday constant [C mol^-1] (default: 96485.33289) N : int, optional number of discretization grid segments (default: 200) e : float, optional absolute tolerance for Newton solver convergence (default: 1e-10) maxit : int, optional maximum number of Newton iterations (default: 20) solver: func( funx(x), x0), optional solver to use (default: None, will use own simple Newton solver) potential0: (N+1,) ndarray, optional (default: None) potential initial values concentration0: (M,N+1) ndarray, optional (default: None) concentration initial values """ self.logger = logging.getLogger(__name__) assert len(c) == len(z), "Provide concentration AND charge for ALL ion species!" # TODO: integrate with constructor initialization parameters above # default solver settings self.converged = False # solver's convergence flag self.N = N # discretization segments self.e = e # Newton solver default tolerance self.maxit = maxit # Newton solver maximum iterations # default output settings # self.output = False # let Newton solver output convergence plots... # self.outfreq = 1 # ...at every nth iteration self.label_width = 40 # character width of quantity labels in log # standard governing equations self.potential_pde = self.poisson_pde self.concentration_pde = self.nernst_planck_pde # empty BC self.boundary_conditions = [] # empty constraints self.g = [] # list of constrain functions, not fully implemented / tested # system parameters self.M = len(c) # number of ion species self.c = c # concentrations self.z = z # number charges self.T = T # temperature self.L = L # 1d domain size self.lambda_S = lambda_S # Stern layer thickness self.x0 = x0 # reference position self.delta_u = delta_u # potential difference self.relative_permittivity = relative_permittivity self.vacuum_permittivity = vacuum_permittivity # R = N_A * k_B # (universal gas constant = Avogadro constant * Boltzmann constant) self.R = R self.F = F self.f = F / (R*T) # for convenience # print all quantities to log for i, (c, z) in enumerate(zip(self.c, self.z)): self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( "ion species {:02d} concentration c".format(i), c, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( "ion species {:02d} number charge z".format(i), z, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'temperature T', self.T, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'domain size L', self.L, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'compact layer thickness lambda_S', self.lambda_S, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'reference position x0', self.x0, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'potential difference delta_u', self.delta_u, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'relative permittivity eps_R', self.relative_permittivity, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'vacuum permittivity eps_0', self.vacuum_permittivity, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'universal gas constant R', self.R, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'Faraday constant F', self.F, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'f = F / (RT)', self.f, lwidth=self.label_width)) # scaled units for dimensionless formulation # length unit chosen as Debye length lambda self.l_unit = self.lambda_D # concentration unit is ionic strength self.c_unit = self.I # no time unit for now, only steady state # self.t_unit = self.l_unit**2 / self.Dn # fixes Dn_scaled = 1 self.u_unit = self.R * self.T / self.F # thermal voltage self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'spatial unit [l]', self.l_unit, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'concentration unit [c]', self.c_unit, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'potential unit [u]', self.u_unit, lwidth=self.label_width)) # domain self.L_scaled = self.L / self.l_unit # compact layer self.lambda_S_scaled = self.lambda_S / self.l_unit # reference position self.x0_scaled = self.x0 / self.l_unit # bulk concentrations self.c_scaled = self.c / self.c_unit # potential difference self.delta_u_scaled = self.delta_u / self.u_unit # print scaled quantities to log self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'reduced domain size L*', self.L_scaled, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'reduced compact layer thickness lambda_S*', self.lambda_S_scaled, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'reduced reference position x0*', self.x0_scaled, lwidth=self.label_width)) for i, c_scaled in enumerate(self.c_scaled): self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( "ion species {:02d} reduced concentration c*".format(i), c_scaled, lwidth=self.label_width)) self.logger.info('{:<{lwidth}s} {:> 8.4g}'.format( 'reduced potential delta_u*', self.delta_u_scaled, lwidth=self.label_width)) # per default, no outer Helmholtz plane self.lhs_ohp = np.nan self.rhs_ohp = np.nan # self.xi0 = None # initialize initial value arrays if potential0 is not None: self.ui0 = potential0 / self.u_unit else: self.ui0 = None if concentration0 is not None: self.ni0 = concentration0 / self.c_unit else: self.ni0 = None self.zi0 = None def __init__(self, *args, **kwargs): """Constructor, see init doc string for arguments. Additional Parameters --------------------- solver: str or func (default: None) solver to use. If str, then selected from scipy optimizers. options: dict, optional (default: None) options object for scipy solver """ self.init(*args, **kwargs) if 'solver' in kwargs: self.solver = kwargs['solver'] else: self.solver = self.newton if 'options' in kwargs: self.options = kwargs['options'] else: self.options = None self.discretize()
43,992
38.56205
120
py
matscipy
matscipy-master/matscipy/electrochemistry/continuous2discrete.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """ Generates atomic structure following a given distribution. Copyright 2019, 2020 IMTEK Simulation University of Freiburg Authors: Johannes Hoermann <[email protected]> Lukas Elflein <[email protected]> """ import logging import os import os.path import sys from six.moves import builtins from collections.abc import Iterable import numpy as np import scipy.constants as sc from scipy import integrate, optimize logger = logging.getLogger(__name__) def exponential(x, rate=0.1): """Exponential distribution.""" return rate * np.exp(-1 * rate * x) def uniform(x, *args, **kwargs): """Uniform distribution.""" return np.ones(np.array(x).shape) / 2 def pdf_to_cdf(pdf): """Transform partial distribution to cumulative distribution function >>> pdf_to_cdf(pdf=np.array([0.5, 0.3, 0.2])) array([ 0.5, 0.8, 1. ]) """ cdf = np.cumsum(pdf) cdf /= cdf[-1] return cdf def get_nearest_pos(array, value): """Find the value of an array clostest to the second argument. Example: >>> get_nearest_pos(array=[0, 0.25, 0.5, 0.75, 1.0], value=0.55) 2 """ array = np.asarray(array) pos = np.abs(array - value).argmin() return pos def get_histogram(struc, box, n_bins=100): """Slice the list of atomic positions, aggregate positions into histogram.""" # Extract x/y/z positions only # x, y, z = struc[:, 0], struc[:, 1], struc[:, 2] histograms = [] for dimension in range(struc.shape[1]): bins = np.linspace(0, box[dimension], n_bins) hist, bins = np.histogram(struc[:, dimension], bins=bins, density=True) # Normalize the histogram for all values to sum to 1 hist /= sum(hist) histograms += [(hist, bins)] return histograms def quartile_function(distribution, p, support=None): """Inverts a distribution x->p, and returns the x-value belonging to the provided p. Assumption: The distribution to be inverted must have a strictly increasing CDF! Also see 'https://en.wikipedia.org/wiki/Quantile_function'. Parameters ---------- distribution: a function x -> p; x should be approximable by a compact support p: an output of the distribution function, probabilities in (0,1) are preferable support: interval to evaluate distribution function on, default: [0,1) in steps of 0.01 """ if support is None: # Define the x-values to evaluate the function on support = np.arange(0, 1, 0.01) # Calculate the histogram of the distribution hist = distribution(support) # Sum the distribution to get the cumulative distribution cdf = pdf_to_cdf(hist) # If the p is not in the image of the support, get the nearest hit instead nearest_pos = get_nearest_pos(cdf, p) # Get the x-value belonging to the probability value provided in the input x = support[nearest_pos] return x def inversion_sampler(distribution, support): """Wrapper for quartile_function.""" # z is distributed according to the given distribution # To approximate this, we insert an atom with probability dis(z) at place z. # This we do by inverting the distribution, and sampling uniformly from distri^-1: p = np.random.uniform() sample = quartile_function(distribution, p, support=support) return sample def rejection_sampler(distribution, support=(0.0, 1.0), max_tries=10000, scale_M=1.1): """Sample distribution by drawing from support and keeping according to distribution. Draw a random sample from our support, and keep it if another random number is smaller than our target distribution at the support location. Algorithm: https://en.wikipedia.org/wiki/Rejection_sampling Parameters ---------- distribution: callable(x) target distribution support: list or 2-tuple either discrete list of locations in space where our distribution is defined, or 2-tuple defining continuous support interval max_tries: how often the sampler should attempt to draw before giving up. If the distribution is very sparse, increase this parameter to still get results. scale_M: float, optional scales bound M for likelihood ratio Returns ------- sample: a location which is consistent (in expectation) with being drawn from the distribution. """ # rejection sampling (https://en.wikipedia.org/wiki/Rejection_sampling): # Generates sampling values from a target distribution X with arbitrary # probability density function f(x) by using a proposal distribution Y # with probability density g(x). # Concept: Generates a sample value from X by instead sampling from Y and # accepting this sample with probability f(x) / ( M g(x) ), repeating the # draws from Y until a value is accepted. M here is a constant, finite bound # on the likelihood ratio f(x)/g(x), satisfying 1 < M < infty over the # support of X; in other words, M must satisfy f(x) <= Mg(x) for all values # of x. The support of Y must include the support of X. # Here, f(x) = distribution(x), g(x) is uniform density on [0,1) # X are f-distributed positions from support, Y are uniformly distributed # values from [0,1)] logger.debug("Rejection sampler on distribution f(x) ({}) with".format( distribution)) # continuous support case if isinstance(support, tuple) and len(support) == 2: a = support[0] b = support[1] logger.debug("continuous support X (interval [{},{}]".format(a, b)) # uniform probability density g(x) on support is g = 1 / (b - a) # find maximum value fmax on distribution at x0 xatol = (b - a)*1e-6 # optimization absolute tolerance x0 = optimize.minimize_scalar(lambda x: -distribution(x), bounds=(a, b), method='bounded', options={'xatol': xatol}).x fmax = distribution(x0) M = scale_M*fmax / g logger.debug("Uniform probability density g(x) = {:g} and".format(g)) logger.debug("maximum probability density f(x0) = {:g} at x0 = {:g}".format(fmax, x0)) logger.debug("require M >= scale_M*g(x)/max(f(x)), i.e. M = {:g}.".format(M)) for _ in range(max_tries): # draw a sample from a uniformly distributed support sample = np.random.random() * (b-a) + a # Generate random float in the half-open interval [0.0, 1.0) and . # keep sample with probability of distribution if np.random.random() < distribution(sample) / (M*g): return sample else: # discrete support case logger.debug("discrete support X ({:d} points in interval [{},{}]".format( len(support), np.min(support), np.max(support))) # uniform probability density g(x) on support is g = 1.0 / len(support) # for discrete support # maximum probability on distribution f(x) is fmax = np.max(distribution(support)) # thus M must be at least M = scale_M * fmax / g logger.debug("Uniform probability g(x) = {:g} and".format(g)) logger.debug("maximum probability max(f(x)) = {:g} require".format(fmax)) logger.debug("M >= scale_M*g(x)/max(f(x)), i.e. M = {:g}.".format(M)) for _ in range(max_tries): # draw a sample from support sample = np.random.choice(support) # Generate random float in the half-open interval [0.0, 1.0) and . # keep sample with probability of distribution if np.random.random() < distribution(sample) / (M*g): return sample raise RuntimeError('Maximum of attempts max_tries {} exceeded!'.format(max_tries)) def generate_structure(distribution, box=np.array([50, 50, 100]), count=100, n_gridpoints=np.nan): """Generate 'atoms' from continuous distribution(s). Coordinates are distributed according to given distributions. Per default, X and Y coordinates are drawn uniformly. Parameters ---------- distribution: func(x) or list of func(x) With one function, uniform sampling applies along x and y axes, while applying 'distribution' along z axis. With a list of functions, applies the respective distribution function along x, y and z direction. box: np.ndarray(3), optional (default: np.array([50, 50, 100]) ) dimensions of volume to be filled with samples count: int, optional (default: 100) number of samples to draw n_gridpoints: int or (int,int,int), optional (default: np.nan) If specified, samples are not placed arbitrarily, but on an evenly spaced grid of this many grid points along each axis. Specify np.nan for continuous sampling, i.e. (10,np.nan,20) Returns ------- np.ndarray((sample_size,3)): sample coordinates """ global logger if callable(distribution): logger.info("Using uniform distribution along x and y direction.") logger.info("Using distribution {} along z direction.".format( distribution)) distribution = [uniform, uniform, distribution] for d in distribution: assert callable(d), "distribution {} must be callable".format(d) assert np.array(box).shape == (3,), "wrong specification of 3d box dimensions" if not isinstance(n_gridpoints, Iterable): n_gridpoints = 3*[n_gridpoints] # to list n_gridpoints = np.array(n_gridpoints, dtype=float) logger.info("Using {} grid as sampling support.".format( n_gridpoints)) assert n_gridpoints.shape == (3,), "n_gridpoints must be int or list of int" # We define which positions in space the atoms can be placed support = [] normalized_distribution = [] for k, d in enumerate(distribution): # Using the box parameter, we construct a grid inside the box # This results in a 100x100x100 grid: if np.isnan(n_gridpoints[k]): # continuous support support.append((0, box[k])) # interval # Normalization constant: Z, _ = integrate.quad(d, support[-1][0], support[-1][1]) else: # discrete support support.append(np.linspace(0, box[k], n_gridpoints[k])) Z = np.sum(d(support[-1])) # Normalization constant logger.info("Normalizing 'distribution' {} by {}.".format(d, Z)) normalized_distribution.append( lambda x, k=k, Z=Z: distribution[k](x) / Z) # For every atom, draw random x, y and z coordinates positions = np.array([[ rejection_sampler(d, s) for d, s in zip(normalized_distribution, support)] for _ in range(int(count))]) logger.info("Drew {} samples from distributions.".format(positions.shape)) return positions
11,737
37.485246
99
py
matscipy
matscipy-master/matscipy/electrochemistry/__init__.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # 2014-2016 Lars Pastewka (U. Freiburg) # 2015-2016 Adrien Gola (KIT) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # from .poisson_boltzmann_distribution import ionic_strength, debye from .poisson_nernst_planck_solver import PoissonNernstPlanckSystem from .continuous2discrete import generate_structure as continuous2discrete from .continuous2discrete import get_histogram
1,188
43.037037
74
py
matscipy
matscipy-master/matscipy/electrochemistry/poisson_nernst_planck_solver_fenics.py
# # Copyright 2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """ Compute ion concentrations consistent with general Poisson-Nernst-Planck (PNP) equations via FEniCS. Copyright 2019 IMTEK Simulation University of Freiburg Authors: Johannes Hoermann <[email protected]> """ import numpy as np import scipy.interpolate import fenics as fn from matscipy.electrochemistry.poisson_nernst_planck_solver import PoissonNernstPlanckSystem class Boundary(fn.SubDomain): """Mark a point to be within the domain boundary for fenics.""" # Boundary causes crash kernel if __init__ doe not call super().__init__() def __init__(self, x0=0, tol=1e-14): super().__init__() self.tol = tol self.x0 = x0 def inside(self, x, on_boundary): """Mark a point to be within the domain boundary for fenics.""" return on_boundary and fn.near(x[0], self.x0, self.tol) class PoissonNernstPlanckSystemFEniCS(PoissonNernstPlanckSystem): """Describes and solves a 1D Poisson-Nernst-Planck system, using log concentrations internally""" @property def X(self): return self.mesh.coordinates().flatten() # only 1D def solve(self): """Evoke FEniCS FEM solver. Returns ------- uij : (Ni,) ndarray potential at Ni grid points nij : (M,Nij) ndarray concentrations of M species at Ni grid points lamj: (L,) ndarray value of L Lagrange multipliers """ # weak form and FEM scheme: # in the weak form, u and v are the trial and test functions associated # with the Poisson part, p and q the trial and test functions associated # with the Nernst-Planck part. lam and mu are trial and test functions # associated to constraints introduced via Lagrange multipliers. # w is the whole set of trial functions [u,p,lam] # W is the space all w live in. rho = 0 for i in range(self.M): rho += self.z[i]*self.p[i] source = - 0.5 * rho * self.v * fn.dx laplace = fn.dot(fn.grad(self.u), fn.grad(self.v))*fn.dx poisson = laplace + source nernst_planck = 0 for i in range(self.M): nernst_planck += fn.dot( - fn.grad(self.p[i]) - self.z[i]*self.p[i]*fn.grad(self.u), fn.grad(self.q[i]) )*fn.dx # constraints set up elsewhere F = poisson + nernst_planck + self.constraints fn.solve(F == 0, self.w, self.boundary_conditions) # store results: wij = np.array([self.w(x) for x in self.X]).T self.uij = wij[0, :] # potential self.nij = wij[1:(self.M+1), :] # concentrations self.lamj = wij[(self.M+1):] # Lagrange multipliers return self.uij, self.nij, self.lamj def boundary_L(self, x, on_boundary): """Mark left boundary. Returns True if x on left boundary.""" return on_boundary and fn.near(x[0], self.x0_scaled, self.bctol) def boundary_R(self, x, on_boundary): """Mark right boundary. Returns True if x on right boundary.""" return on_boundary and fn.near(x[0], self.x1_scaled, self.bctol) def boundary_C(self, x, on_boundary): """Mark domain center.""" return fn.near(x[0], (self.x0_scaled + self.x1_scaled)/2., self.bctol) def applyLeftPotentialDirichletBC(self, u0): """FEniCS Dirichlet BC u0 for potential at left boundary.""" self.boundary_conditions.extend([ fn.DirichletBC(self.W.sub(0), u0, lambda x, on_boundary: self.boundary_L(x, on_boundary))]) def applyRightPotentialDirichletBC(self, u0): """FEniCS Dirichlet BC u0 for potential at right boundary.""" self.boundary_conditions.extend([ fn.DirichletBC(self.W.sub(0), u0, lambda x, on_boundary: self.boundary_R(x, on_boundary))]) def applyLeftConcentrationDirichletBC(self, k, c0): """FEniCS Dirichlet BC c0 for k'th ion species at left boundary.""" self.boundary_conditions.extend([ fn.DirichletBC(self.W.sub(k+1), c0, lambda x, on_boundary: self.boundary_L(x, on_boundary))]) def applyRightConcentrationDirichletBC(self, k, c0): """FEniCS Dirichlet BC c0 for k'th ion species at right boundary.""" self.boundary_conditions.extend([ fn.DirichletBC(self.W.sub(k+1), c0, lambda x, on_boundary: self.boundary_R(x, on_boundary))]) def applyCentralReferenceConcentrationConstraint(self, k, c0): """FEniCS Dirichlet BC c0 for k'th ion species at right boundary.""" self.boundary_conditions.extend([ fn.DirichletBC(self.W.sub(k+1), c0, lambda x, on_boundary: self.boundary_C(x, on_boundary))]) # TODO: Robin BC! def applyLeftPotentialRobinBC(self, u0, lam0): self.logger.warning("Not implemented!") def applyRightPotentialRobinBC(self, u0, lam0): self.logger.warning("Not implemented!") def applyNumberConservationConstraint(self, k, c0): """ Enforce number conservation constraint via Lagrange multiplier. See https://fenicsproject.org/docs/dolfin/1.6.0/python/demo/documented/neumann-poisson/python/documentation.html """ self.constraints += self.lam[k]*self.q[k]*fn.dx \ + (self.p[k]-c0)*self.mu[k]*fn.dx def applyPotentialDirichletBC(self, u0, u1): """Potential Dirichlet BC u0 and u1 on left and right boundary.""" self.applyLeftPotentialDirichletBC(u0) self.applyRightPotentialDirichletBC(u1) def applyPotentialRobinBC(self, u0, u1, lam0, lam1): """Potential Robin BC on left and right boundary.""" self.applyLeftPotentialRobinBC(u0, lam0) self.applyRightPotentialRobinBC(u1, lam1) def useStandardInterfaceBC(self): """Interface at left hand side and open bulk at right hand side""" self.boundary_conditions = [] # Potential Dirichlet BC self.u0 = self.delta_u_scaled self.u1 = 0 self.logger.info('Left hand side Dirichlet boundary condition: u0 = {:> 8.4g}'.format(self.u0)) self.logger.info('Right hand side Dirichlet boundary condition: u1 = {:> 8.4g}'.format(self.u1)) self.applyPotentialDirichletBC(self.u0, self.u1) for k in range(self.M): self.logger.info(('Ion species {:02d} right hand side concentration ' 'Dirichlet boundary condition: c1 = {:> 8.4g}').format(k, self.c_scaled[k])) self.applyRightConcentrationDirichletBC(k, self.c_scaled[k]) def useStandardCellBC(self): """ Interfaces at left hand side and right hand side, species-wise number conservation within interval.""" self.boundary_conditions = [] # Introduce a Lagrange multiplier per species anderson # rebuild discretization scheme (function spaces) self.K = self.M self.discretize() # Potential Dirichlet BC self.u0 = self.delta_u_scaled / 2. self.u1 = - self.delta_u_scaled / 2. self.logger.info('{:>{lwidth}s} u0 = {:< 8.4g}'.format( 'Left hand side Dirichlet boundary condition', self.u0, lwidth=self.label_width)) self.logger.info('{:>{lwidth}s} u1 = {:< 8.4g}'.format( 'Right hand side Dirichlet boundary condition', self.u1, lwidth=self.label_width)) self.applyPotentialDirichletBC(self.u0, self.u1) # Number conservation constraints self.constraints = 0 N0 = self.L_scaled*self.c_scaled # total amount of species in cell for k in range(self.M): self.logger.info('{:>{lwidth}s} N0 = {:<8.4g}'.format( 'Ion species {:02d} number conservation constraint'.format(k), N0[k], lwidth=self.label_width)) self.applyNumberConservationConstraint(k, self.c_scaled[k]) def useCentralReferenceConcentrationBasedCellBC(self): """ Interfaces at left hand side and right hand side, species-wise concentration fixed at cell center.""" self.boundary_conditions = [] # Introduce a Lagrange multiplier per species anderson # rebuild discretization scheme (function spaces) # self.K = self.M # self.discretize() # Potential Dirichlet BC self.u0 = self.delta_u_scaled / 2. self.u1 = - self.delta_u_scaled / 2. self.logger.info('{:>{lwidth}s} u0 = {:< 8.4g}'.format( 'Left hand side Dirichlet boundary condition', self.u0, lwidth=self.label_width)) self.logger.info('{:>{lwidth}s} u1 = {:< 8.4g}'.format( 'Right hand side Dirichlet boundary condition', self.u1, lwidth=self.label_width)) self.applyPotentialDirichletBC(self.u0, self.u1) for k in range(self.M): self.logger.info( 'Ion species {:02d} reference concentration condition: c1 = {:> 8.4g} at cell center'.format( k, self.c_scaled[k])) self.applyCentralReferenceConcentrationConstraint(k, self.c_scaled[k]) def useSternLayerCellBC(self): """ Interfaces at left hand side and right hand side, species-wise number conservation within interval.""" self.boundary_conditions = [] # Introduce a Lagrange multiplier per species anderson # rebuild discretization scheme (function spaces) self.constraints = 0 self.K = self.M self.discretize() # Potential Dirichlet BC self.u0 = self.delta_u_scaled / 2. self.u1 = - self.delta_u_scaled / 2. boundary_markers = fn.MeshFunction( 'size_t', self.mesh, self.mesh.topology().dim()-1) bx = [ Boundary(x0=self.x0_scaled, tol=self.bctol), Boundary(x0=self.x1_scaled, tol=self.bctol)] # Boundary.mark crashes the kernel if Boundary is internal class for i, b in enumerate(bx): b.mark(boundary_markers, i) boundary_conditions = { 0: {'Robin': (1./self.lambda_S_scaled, self.u0)}, 1: {'Robin': (1./self.lambda_S_scaled, self.u1)}, } ds = fn.Measure('ds', domain=self.mesh, subdomain_data=boundary_markers) integrals_R = [] for i in boundary_conditions: if 'Robin' in boundary_conditions[i]: r, s = boundary_conditions[i]['Robin'] integrals_R.append(r*(self.u-s)*self.v*ds(i)) self.constraints += sum(integrals_R) # Number conservation constraints N0 = self.L_scaled*self.c_scaled # total amount of species in cell for k in range(self.M): self.logger.info('{:>{lwidth}s} N0 = {:<8.4g}'.format( 'Ion species {:02d} number conservation constraint'.format(k), N0[k], lwidth=self.label_width)) self.applyNumberConservationConstraint(k, self.c_scaled[k]) def discretize(self): """Builds function space, call again after introducing constraints""" # FEniCS interface self.mesh = fn.IntervalMesh(self.N, self.x0_scaled, self.x1_scaled) # http://www.femtable.org/ # Argyris* ARG # Arnold-Winther* AW # Brezzi-Douglas-Fortin-Marini* BDFM # Brezzi-Douglas-Marini BDM # Bubble B # Crouzeix-Raviart CR # Discontinuous Lagrange DG # Discontinuous Raviart-Thomas DRT # Hermite* HER # Lagrange CG # Mardal-Tai-Winther* MTW # Morley* MOR # Nedelec 1st kind H(curl) N1curl # Nedelec 2nd kind H(curl) N2curl # Quadrature Q # Raviart-Thomas RT # Real R # construct test and trial function space from elements # spanned by Lagrange polynomials for the physical variables of # potential and concentration and global elements with a single degree # of freedom ('Real') for constraints. # For an example of this approach, refer to # https://fenicsproject.org/docs/dolfin/latest/python/demos/neumann-poisson/demo_neumann-poisson.py.html # For another example on how to construct and split function spaces # for solving coupled equations, refer to # https://fenicsproject.org/docs/dolfin/latest/python/demos/mixed-poisson/demo_mixed-poisson.py.html P = fn.FiniteElement('Lagrange', fn.interval, 3) R = fn.FiniteElement('Real', fn.interval, 0) elements = [P]*(1+self.M) + [R]*self.K H = fn.MixedElement(elements) self.W = fn.FunctionSpace(self.mesh, H) # solution functions self.w = fn.Function(self.W) # set initial values if available P = fn.FunctionSpace(self.mesh, 'P', 1) dof2vtx = fn.vertex_to_dof_map(P) if self.ui0 is not None: x = np.linspace(self.x0_scaled, self.x1_scaled, self.ui0.shape[0]) ui0 = scipy.interpolate.interp1d(x, self.ui0) # use linear interpolation on mesh self.u0_func = fn.Function(P) self.u0_func.vector()[:] = ui0(self.X)[dof2vtx] fn.assign(self.w.sub(0), fn.interpolate(self.u0_func, self.W.sub(0).collapse())) if self.ni0 is not None: x = np.linspace(self.x0_scaled, self.x1_scaled, self.ni0.shape[1]) ni0 = scipy.interpolate.interp1d(x, self.ni0) self.p0_func = [fn.Function(P)]*self.ni0.shape[0] for k in range(self.ni0.shape[0]): self.p0_func[k].vector()[:] = ni0(self.X)[k, :][dof2vtx] fn.assign(self.w.sub(1+k), fn.interpolate(self.p0_func[k], self.W.sub(k+1).collapse())) # u represents voltage , p concentrations uplam = fn.split(self.w) self.u, self.p, self.lam = ( uplam[0], [*uplam[1:(self.M+1)]], [*uplam[(self.M+1):]]) # v, q and mu represent respective test functions vqmu = fn.TestFunctions(self.W) self.v, self.q, self.mu = ( vqmu[0], [*vqmu[1:(self.M+1)]], [*vqmu[(self.M+1):]]) def __init__(self, *args, **kwargs): self.init(*args, **kwargs) # TODO: don't hard code btcol self.bctol = 1e-14 # tolerance for identifying domain boundaries self.K = 0 # number of Lagrange multipliers (constraints) self.constraints = 0 # holds constraint kernels self.discretize()
15,709
39.699482
120
py
matscipy
matscipy-master/matscipy/tool/plot.py
# # Copyright 2016, 2021 Lars Pastewka (U. Freiburg) # 2016 Adrien Gola (KIT) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """ Usage : python plot.py [filename] This tool script allow to quicly plot data from text files arranged in column with space as separator. It uses a GUI through Tkinter "log.lammp" can be read and splited according to different "run" present in the log file Adrien Gola // 4.11.2015 """ import numpy as np import matplotlib matplotlib.rcParams['backend'] = "Qt4Agg" import matplotlib.pyplot as p import os,sys import os.path import Tkinter as tk import ttk # ------------------------------------ # ------- Function definition -------- # ------------------------------------ def close_windows(): root.destroy() def plot_button(): global xlabel,ylabel x = d[:,Xvar.get()] y = d[:,Yvar.get()] if xlabel.get() != "X-axis label": hx = xlabel.get() else: hx = h[Xvar.get()] if ylabel.get() != "Y-axis label": hy = ylabel.get() else: hy = h[Yvar.get()] p.plot(x, y, 'o') p.xlabel(hx) p.ylabel(hy) p.show() def process_file(): global variables_frame,h,d,Xvar,Yvar,skipline,flag_loglammps selected_file = sorted(outlogfiles)[Fvar.get()] if flag_loglammps: h = open(selected_file,'r').readlines()[0].strip('#').strip().split(" ") # headers list d = np.loadtxt(selected_file, skiprows=1) # data else: h = filter(None,open(selected_file,'r').readlines()[0+int(skipline.get())].strip('#').strip().split(" ")) # headers list d = np.loadtxt(selected_file, skiprows=1+int(skipline.get())) # data try: for child in variables_frame.winfo_children(): child.destroy() except: pass #Xvar tk.Label(variables_frame,text="Select X-axis variable to plot",anchor='n').grid(row=next_row+1) Xvar = tk.IntVar() for i,x in enumerate(h): x_row=i+2 tk.Radiobutton(variables_frame,text=x,variable=Xvar, value=i).grid(row=next_row+x_row) #Yvar tk.Label(variables_frame,text="Select Y-axis variable to plot",anchor='n').grid(row=next_row+1,column=1) Yvar = tk.IntVar() for j,x in enumerate(h): y_row=j+2 tk.Radiobutton(variables_frame,text=x,variable=Yvar, value=j).grid(row=next_row+y_row,column=1) mypath = os.getcwd() # ------------------------------------------------------- # ------- Reading and spliting the main log file -------- # ------------------------------------------------------- flag_loglammps=0 # --- file selection --- try : in_file = sys.argv[1] except: print("Usage : plot_general.py file_name") quit() if in_file == "log.lammps": flag_loglammps=1 data = open("log.lammps",'r').readlines() # select log.lammps as main log file if it exists # --- spliting into "out.log.*" files --- j = 0 flag = 0 flag_out = 0 step = "" for lines in data: lines = lines.strip() if lines.startswith("run:"): step = "."+lines.strip().strip("run: ") elif lines.startswith("Memory usage per processor"): if len(str(j)) == 1: J = "0"+str(j) else: J = str(j) out = open("out.log.%s%s-plt-tmp"%(J,step),'w') flag_out = 1 flag = 1 elif flag and lines.startswith("Loop") or lines.startswith("kill"): flag = 0 j+=1 out.close() step = "" elif flag: out.write(lines+'\n') if flag_out: out.close() outlogfiles = [ f for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath,f)) and f.startswith("out.log") and f.endswith("plt-tmp")] # list of "out.log.*" files else: outlogfiles = [in_file] pass ################### ### MAIN script ### ################### root=tk.Tk() # Positioning frames button_frame = tk.Frame(root,heigh=5) button_frame.pack(side='right') source_frame = tk.Frame(root) source_frame.pack() labels_frame = tk.Frame(root) labels_frame.pack(side="bottom") variables_frame = tk.Frame(root) variables_frame.pack(side="bottom") # Filling frames tk.Label(source_frame,text="Select data source",anchor='n').grid(row=0) Fvar = tk.IntVar() for i,x in enumerate(outlogfiles): next_row=i+1 tk.Radiobutton(source_frame,text=x,variable=Fvar, value=i, command = process_file).grid(row=next_row) if not flag_loglammps: skipline = tk.Entry(source_frame,width=5,justify="center") skipline.grid(row=next_row,column=1) skipline.insert(0,0) else: skipline=0 next_row+=1 ttk.Separator(source_frame,orient='horizontal').grid(row=next_row,columnspan=2,sticky="ew") # Insert X,Y label text field ttk.Separator(labels_frame,orient='horizontal').grid(columnspan=2,sticky="ew") xlabel = tk.Entry(labels_frame,width=50,justify="center") xlabel.grid(row=next_row+1,column=0,columnspan=2) xlabel.insert(0,"X-axis label") ylabel = tk.Entry(labels_frame,width=50,justify="center") ylabel.grid(row=next_row+2,column=0,columnspan=2) ylabel.insert(0,"Y-axis label") close = tk.Button(button_frame, text = "Close",width=10, command = close_windows) close.grid(row=1) plot = tk.Button(button_frame, text = "Plot",width=10, command = plot_button) plot.grid(row=0) # show GUI root.mainloop() # Cleaning tmp files if flag_loglammps: for f in outlogfiles: os.remove(f)
6,316
30.272277
174
py
matscipy
matscipy-master/matscipy/tool/__init__.py
# # Copyright 2014-2015, 2021 Lars Pastewka (U. Freiburg) # 2015-2016 Adrien Gola (KIT) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # Generic stuff may go here.
915
35.64
71
py
matscipy
matscipy-master/examples/fracture_mechanics/make_crack_thin_strip/params.py
# # Copyright 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # from ase.lattice import bulk import ase.units as units # ********** Bulk unit cell ************ # 8-atom diamond cubic unit cell for silicon a0 = 5.44 # guess at lattice constant for Si - we will minimize cryst = bulk('Si', 'diamond', a=a0, cubic=True) surf_ny = 4 # number of cells needed to get accurate surface energy # ********* System parameters ********** # There are three possible crack systems, choose one and uncomment it # System 1. (111)[0-11] crack_direction = (-2, 1, 1) # Miller index of x-axis cleavage_plane = (1, 1, 1) # Miller index of y-axis crack_front = (0, 1, -1) # Miller index of z-axis # # System 2. (110)[001] # crack_direction = (1,-1,0) # cleavage_plane = (1,1,0) # crack_front = (0,0,1) # # System 3. (110)[1-10] # crack_direction = (0,0,-1) # cleavage_plane = (1,1,0) # crack_front = (1,-1,0) check_rotated_elastic_constants = False width = 200.0*units.Ang # Width of crack slab height = 100.0*units.Ang # Height of crack slab vacuum = 100.0*units.Ang # Amount of vacuum around slab crack_seed_length = 40.0*units.Ang # Length of seed crack strain_ramp_length = 30.0*units.Ang # Distance over which strain is ramped up initial_G = 5.0*(units.J/units.m**2) # Initial energy flow to crack tip relax_bulk = True # If True, relax initial bulk cell bulk_fmax = 1e-6*units.eV/units.Ang # Max force for bulk, C_ij and surface energy relax_slab = True # If True, relax notched slab with calculator relax_fmax = 0.025*units.eV/units.Ang # Maximum force criteria for relaxation # ******* Molecular dynamics parameters *********** sim_T = 300.0*units.kB # Simulation temperature nsteps = 10000 # Total number of timesteps to run for timestep = 1.0*units.fs # Timestep (NB: time base units are not fs!) cutoff_skin = 2.0*units.Ang # Amount by which potential cutoff is increased # for neighbour calculations tip_move_tol = 10.0 # Distance tip has to move before crack # is taken to be running strain_rate = 1e-5*(1/units.fs) # Strain rate traj_file = 'traj.nc' # Trajectory output file (NetCDF format) traj_interval = 10 # Number of time steps between # writing output frames # ********** Setup calculator ************ # Stillinger-Weber (SW) classical interatomic potential, from QUIP from quippy import Potential calc = Potential('IP SW', 'params.xml') # Screened Kumagai potential, from Atomistica #import atomistica #calc = atomistica.KumagaiScr()
3,464
37.076923
83
py
matscipy
matscipy-master/examples/fracture_mechanics/ideal_brittle_solid/params.py
# # Copyright 2014, 2018 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # N = 20 M = 20 # number of extra cols to add when we extend rc = 1.2 k = 1.0 a = 1.0 vacuum = 30.0 delta = 1.0 dt = 0.025 beta = 0.01 strain_rate = 1e-4
946
30.566667
71
py
matscipy
matscipy-master/examples/fracture_mechanics/energy_barrier/params.py
# # Copyright 2015 James Kermode (Warwick U.) # 2014 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # from math import log import numpy as np import ase.io from matscipy.fracture_mechanics.clusters import diamond_111_110 import atomistica ### # Interaction potential calc = atomistica.KumagaiScr() # Fundamental material properties el = 'Si' a0 = 5.429 C11 = 166. # GPa C12 = 65. # GPa C44 = 77. # GPa surface_energy = 1.08 * 10 # GPa*A = 0.1 J/m^2 # Crack system n = [ 6, 4, 1 ] crack_surface = [ 1, 1, 1 ] crack_front = [ 1, -1, 0 ] vacuum = 6.0 # Simulation control k1 = 0.900 bond_lengths = np.linspace(2.5, 4.5, 21) fmax = 0.001 cutoff = 5.0 # Setup crack system cryst = diamond_111_110(el, a0, n, crack_surface, crack_front) ase.io.write('cryst.cfg', cryst) optimize_tip_position = True basename = 'k_%04d' % int(k1*1000.0)
1,717
24.641791
71
py
matscipy
matscipy-master/examples/fracture_mechanics/quartz_crack/params.py
# # Copyright 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os import numpy as np from ase.atoms import Atoms from ase.io import read, write from ase.calculators.neighborlist import NeighborList from ase.units import GPa, J, m nx = 8 slab_height = 35.0 final_height = 27.0 vacuum = 10.0 tetra = True terminate = False skin = 4.0 k1 = 1.0 bond = (190, 202) bond_lengths = np.linspace(1.6, 2.5, 11) fmax = 0.1 crack_surface = [1, 0, 1] crack_front = [0,1,0] aq = Atoms(symbols='Si3O6', pbc=True, cell=np.array( [[ 2.51418 , -4.3546875, 0. ], [ 2.51418 , 4.3546875, 0. ], [ 0. , 0. , 5.51193 ]]), positions=np.array( [[ 1.21002455, -2.095824 , 3.67462 ], [ 1.21002455, 2.095824 , 1.83731 ], [-2.4200491 , 0. , -0. ], [ 1.66715276, -0.73977431, 4.42391176], [-0.19291303, 1.8136838 , 8.09853176], [-1.47423973, -1.07390948, 6.26122176], [ 1.66715276, 0.73977431, -4.42391176], [-1.47423973, 1.07390948, -0.74929176], [-0.19291303, -1.8136838 , -2.58660176]])) if not os.path.exists('slab.xyz'): from quippy.structures import rotation_matrix from quippy.surface import orthorhombic_slab from quippy.atoms import Atoms as QuippyAtoms aq = QuippyAtoms(aq) slab = orthorhombic_slab(aq, rot=rotation_matrix(aq, crack_surface, crack_front), periodicity=[0.0, slab_height, 0.0], vacuum=[0.0, vacuum, 0.0], verbose=True) write('slab.xyz', slab) atoms = read('slab.xyz') eqm_bond_lengths = {(8, 14): 1.60, (1, 8): 1.10} # Quartz elastic constants computed with DFT (PBE-GGA) C = np.zeros((6,6)) C[0,0] = C[1,1] = 87.1*GPa C[0,1] = C[1,0] = -7.82*GPa C[0,2] = C[2,0] = C[0,3] = C[3,0] = 6.30*GPa C[0,3] = C[3,0] = -17.0*GPa C[1,3] = C[3,1] = -C[0,3] C[4,5] = C[0,3] C[5,4] = C[0,3] C[2,2] = 87.1*GPa C[3,3] = 49.1*GPa C[4,4] = 49.1*GPa C[5,5] = 47.5*GPa # Surface energy computed with DFT (PBE-GGA) surface_energy = 0.161*(J/m**2)*10 a = atoms.copy() b = a * [nx, 1, 1] b.center() b.positions[:,0] += 0.5 b.set_scaled_positions(b.get_scaled_positions()) mask = ((b.positions[:,0] > 0.) & (b.positions[:,0] < 2*a.cell[0,0]) & (b.positions[:,1] < (a.cell[1,1]/2.0 + final_height/2.0)) & (b.positions[:,1] > (a.cell[1,1]/2.0 - final_height/2.0))) nl = NeighborList([1.0]*len(b), self_interaction=False, bothways=True) nl.update(b) term = Atoms() if tetra: for i in range(len(b)): if not mask[i]: continue indices, offsets = nl.get_neighbors(i) if b.numbers[i] == 8 and mask[indices].sum() == 0: mask[i] = False if b.numbers[i] == 14: # complete tetrahedra for (j, o) in zip(indices, offsets): if b.numbers[j] == 8: mask[j] = True if terminate: for i in range(len(b)): if not mask[i]: continue indices, offsets = nl.get_neighbors(i) for (j, o) in zip(indices, offsets): if mask[j]: continue # i is IN, j is OUT, we need to terminate cut bond ij z1 = b.numbers[i] z2 = b.numbers[j] print 'terminating %d-%d bond (%d, %d)' % (z1, z2, i, j) if z1 != 8: raise ValueError('all IN term atoms must be O') r_ij = (b.positions[j] + np.dot(o, b.cell) - b.positions[i]) t = Atoms('H') d = r_ij/(eqm_bond_lengths[min(z1,z2), max(z1,z2)]* eqm_bond_lengths[min(z1, 1), max(z1, 1)]) t.translate(b.positions[i] + d) term += t cryst = b[mask] + term # calculator from quippy import Potential calc = Potential('IP TS', param_filename='ts_params.xml') cryst.set_calculator(calc) cryst.get_potential_energy() # obtain reference dipole moments cryst.set_scaled_positions(cryst.get_scaled_positions()) cryst.positions[:,0] += cryst.cell[0,0]/2. - cryst.positions[:,0].mean() cryst.positions[:,1] += cryst.cell[1,1]/2. - cryst.positions[:,1].mean() cryst.set_scaled_positions(cryst.get_scaled_positions()) cryst.center(vacuum, axis=0) cryst.center(vacuum, axis=1) # fix atoms near outer boundaries r = cryst.get_positions() minx = r[:, 0].min() + skin maxx = r[:, 0].max() - skin miny = r[:, 1].min() + skin maxy = r[:, 1].max() - skin g = np.where( np.logical_or( np.logical_or( np.logical_or( r[:, 0] < minx, r[:, 0] > maxx), r[:, 1] < miny), r[:, 1] > maxy), np.zeros(len(cryst), dtype=int), np.ones(len(cryst), dtype=int)) cryst.set_array('groups', g) # zero dipole moments on outer boundaries #cryst.set_array('fixdip', np.logical_not(g)) #cryst.set_array('dipoles', calc.atoms.arrays['dipoles']) #cryst.arrays['dipoles'][g==0, :] = 0.0 write('cryst.xyz', cryst, format='extxyz')
5,773
29.550265
81
py
matscipy
matscipy-master/examples/fracture_mechanics/quasistatic_crack/params.py
# # Copyright 2016 James Kermode (Warwick U.) # 2014 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # from math import log import numpy as np import ase.io from matscipy.fracture_mechanics.clusters import diamond, set_groups import atomistica ### # Interaction potential calc = atomistica.KumagaiScr() # Fundamental material properties el = 'Si' a0 = 5.429 C11 = 166. # GPa C12 = 65. # GPa C44 = 77. # GPa surface_energy = 1.08 * 10 # GPa*A = 0.1 J/m^2 # Crack system n = [ 4, 6, 1 ] crack_surface = [ 1,-1, 0 ] crack_front = [ 1, 1, 0 ] crack_tip = [ 41, 56 ] skin_x, skin_y = 1, 1 vacuum = 6.0 # Simulation control nsteps = 31 # Increase stress intensity factor k1 = np.linspace(0.8, 1.5, nsteps) # Don't move crack tip tip_dx = np.zeros_like(k1) tip_dz = np.zeros_like(k1) fmax = 0.05 # Setup crack system cryst = diamond(el, a0, n, crack_surface, crack_front) set_groups(cryst, n, skin_x, skin_y) ase.io.write('cryst.cfg', cryst) # Compute crack tip position r0 = np.sum(cryst.get_positions()[crack_tip,:], axis=0)/len(crack_tip) tip_x0, tip_y0, tip_z0 = r0
1,969
25.986301
71
py
matscipy
matscipy-master/examples/fracture_mechanics/energy_barrier_multiple/params.py
# # Copyright 2014 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # from math import log import numpy as np import ase.io from matscipy.fracture_mechanics.clusters import diamond_110_001 import atomistica ### # Interaction potential calc = atomistica.KumagaiScr() # Fundamental material properties el = 'Si' a0 = 5.429 C11 = 166. # GPa C12 = 65. # GPa C44 = 77. # GPa surface_energy = 1.08 * 10 # GPa*A = 0.1 J/m^2 # Crack system n = [ 6, 6, 1 ] crack_surface = [ 1, 1, 0 ] crack_front = [ 0, 0, 1 ] vacuum = 6.0 # Simulation control bonds = [( 58, 59 ), (61, 84)] k1 = 1.00 bond_lengths = np.linspace(2.5, 4.5, 41) fmax = 0.001 # Setup crack system cryst = diamond_110_001(el, a0, n, crack_surface, crack_front) ase.io.write('cryst.cfg', cryst) optimize_tip_position = True
1,694
25.076923
71
py
matscipy
matscipy-master/examples/fracture_mechanics/sinclair_crack/params.py
# # Copyright 2020 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import numpy as np from matscipy.fracture_mechanics.clusters import diamond, set_groups, set_regions import ase.io import atomistica # Interaction potential calc = atomistica.KumagaiScr() # Fundamental material properties el = 'Si' a0 = 5.429 surface_energy = 1.08 * 10 # GPa*A = 0.1 J/m^2 elastic_symmetry = 'cubic' # Crack system crack_surface = [1, 1, 1] crack_front = [1, -1, 0] vacuum = 6.0 # Simulation control ds = 0.01 nsteps = 10000 continuation = True k0 = 0.9 dk = 1e-4 fmax = 1e-2 max_steps = 50 circular_regions = True # circular regions I-II-III-IV if circular_regions: r_I = 15.0 cutoff = 6.0 r_III = 40.0 n = [2 * int((r_III + cutoff)/ a0), 2 * int((r_III + cutoff)/ a0) - 1, 1] print('n=', n) # Setup crack system and regions I, II, III and IV cryst = diamond(el, a0, n, crack_surface, crack_front) cluster = set_regions(cryst, r_I, cutoff, r_III) # carve circular cluster else: # boxy regions, with fixed dimension n n = [20, 19, 1] R_III = 4 R_II = 4 cryst = diamond(el, a0, n, crack_surface, crack_front) set_groups(cryst, n, R_III, R_III) regionIII = cryst.arrays['groups'] == 0 regionI_II = cryst.arrays['groups'] == 1 set_groups(cryst, n, R_II + R_III, R_II + R_III) regionII_III = cryst.arrays['groups'] == 0 regionI = cryst.arrays['groups'] == 1 regionII = regionI_II & regionII_III print(sum(regionI), sum(regionII), sum(regionIII)) cryst.new_array('region', np.zeros(len(cryst), dtype=int)) cryst.arrays['region'][regionI] = 1 cryst.arrays['region'][regionII] = 2 cryst.arrays['region'][regionIII] = 3 del cryst.arrays['groups'] cluster = cryst # cluster and crystal only differ by PBC ase.io.write('cryst.cfg', cryst) ase.io.write('cluster.cfg', cluster)
2,603
25.845361
81
py
matscipy
matscipy-master/examples/socketcalc/quip_socket_client.py
# # Copyright 2015 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import logging #logging.root.setLevel(logging.DEBUG) import os from matscipy.socketcalc import QUIPClient, SocketCalculator from matscipy.fracture_mechanics.clusters import diamond from quippy import Potential quip_client = QUIPClient(client_id=0, exe=os.path.join(os.environ['QUIP_ROOT'], 'build.'+os.environ['QUIP_ARCH'], 'socktest'), param_files=['params.xml'], env=os.environ) sock_calc = SocketCalculator(quip_client) el = 'Si' a0 = 5.43 n = [ 6, 4, 1 ] crack_surface = [ 1, 1, 1 ] crack_front = [ 1, -1, 0 ] cryst = diamond(el, a0, n, crack_surface, crack_front) cryst.pbc = [True, True, True] # QUIP doesn't handle open BCs cryst.rattle(0.01) cryst.set_calculator(sock_calc) sock_e = cryst.get_potential_energy() sock_f = cryst.get_forces() sock_s = cryst.get_stress() sock_calc.shutdown() # compare to results from quippy quippy_calc = Potential('IP SW', param_filename='params.xml') cryst.set_calculator(quippy_calc) quippy_e = cryst.get_potential_energy() quippy_f = cryst.get_forces() quippy_s = cryst.get_stress() print 'energy difference', sock_e - quippy_e print 'force difference', abs((sock_f - quippy_f).max()) print 'stress difference', abs((sock_s - quippy_s).max())
2,180
31.073529
75
py
matscipy
matscipy-master/examples/socketcalc/castep_socket_calc.py
# # Copyright 2019 James Brixey (Warwick U.) # 2016 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import logging logging.root.setLevel(logging.INFO) import sys import os from distutils import spawn from ase.lattice import bulk from ase.io import read from matscipy.socketcalc import CastepClient, SocketCalculator if 'CASTEP_COMMAND' in os.environ: castep = os.environ['CASTEP_COMMAND'] else: castep = spawn.find_executable('castep.serial') atoms = bulk('Si') castep_client = CastepClient(client_id=0, exe=castep, devel_code="""PP=T pp: NL=T SW=T :endpp """) try: sock_calc = SocketCalculator(castep_client) atoms.set_calculator(sock_calc) sock_e = atoms.get_potential_energy() sock_f = atoms.get_forces() sock_s = atoms.get_stress() print('energy', sock_e) print('forces', sock_f) print('stress', sock_s) atoms.cell *= 2.0 # trigger a restart by changing cell sock_e = atoms.get_potential_energy() sock_f = atoms.get_forces() sock_s = atoms.get_stress() print('energy', sock_e) print('forces', sock_f) print('stress', sock_s) atoms.rattle() # small change in position, no restart sock_e = atoms.get_potential_energy() sock_f = atoms.get_forces() sock_s = atoms.get_stress() print('energy', sock_e) print('forces', sock_f) print('stress', sock_s) finally: sock_calc.shutdown()
2,234
26.9375
71
py
matscipy
matscipy-master/examples/socketcalc/vasp_socket_client.py
# # Copyright 2015 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import logging logging.root.setLevel(logging.DEBUG) import os from distutils import spawn from ase import Atoms from matscipy.socketcalc import VaspClient, SocketCalculator # look for mpirun and vasp on $PATH mpirun = spawn.find_executable('mpirun') vasp = spawn.find_executable('vasp') #vasp = '/home/eng/essswb/vasp5/vasp.5.3.new/vasp' a = 5.404 bulk = Atoms(symbols='Si8', positions=[(0, 0, 0.1 / a), (0, 0.5, 0.5), (0.5, 0, 0.5), (0.5, 0.5, 0), (0.25, 0.25, 0.25), (0.25, 0.75, 0.75), (0.75, 0.25, 0.75), (0.75, 0.75, 0.25)], pbc=True) bulk.set_cell((a, a, a), scale_atoms=True) vasp_client = VaspClient(client_id=0, npj=1, ppn=8, exe=vasp, mpirun=mpirun, parmode='mpi', xc='LDA', lreal=False, ibrion=13, nsw=1000000, algo='VeryFast', npar=8, lplane=False, lwave=False, lcharg=False, nsim=1, voskown=1, ismear=0, sigma=0.01, iwavpr=11, isym=0, nelm=150) sock_calc = SocketCalculator(vasp_client) bulk.set_calculator(sock_calc) sock_e = bulk.get_potential_energy() sock_f = bulk.get_forces() sock_s = bulk.get_stress() print 'energy', sock_e print 'forces', sock_f print 'stress', sock_s bulk.rattle(0.01) sock_e = bulk.get_potential_energy() sock_f = bulk.get_forces() sock_s = bulk.get_stress() print 'energy', sock_e print 'forces', sock_f print 'stress', sock_s sock_calc.shutdown()
2,537
29.578313
86
py
matscipy
matscipy-master/examples/hessian_matrix/Hessian_matrix.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2019 Jan Griesser (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import numpy as np from scipy.sparse import csr_matrix from ase.io import NetCDFTrajectory from ase.io import read import matscipy.calculators.pair_potential as calculator # Load atomic configuration MinStructure = NetCDFTrajectory( "structure/PBC.KA.N256.Min.nc", "r", keep_open=True) # Paramters for a binary Kob-Anderson glass. # Kob, Walter, and Hans C. Andersen. Phys. Rev. E 51.5 (1995): 4626. # The interaction is modeled via a quadratic shifted Lennard-Jones potential. parameters = {(1, 1): calculator.LennardJonesQuadratic(1, 1, 3), (1, 2): calculator.LennardJonesQuadratic( 1.5, 0.8, 2.4), (2, 2): calculator.LennardJonesQuadratic(0.5, 0.88, 2.64)} a = calculator.PairPotential(parameters) # Exemplary code for the calculation of the full hessian matrix. # Sparse H_sparse = a.calculate_hessian_matrix( MinStructure[len(MinStructure)-1], "sparse") # Dense H_dense = a.calculate_hessian_matrix( MinStructure[len(MinStructure)-1], "dense") # Compute the only rows of the Hessian matrix which correspong to atom Ids = 5,6 H_sparse1 = a.calculate_hessian_matrix( MinStructure[len(MinStructure)-1], "sparse", limits=(5, 7))
1,989
38.019608
106
py
matscipy
matscipy-master/examples/opls/extxyz_to_lammps.py
#!/usr/bin/env python3 # # Copyright 2023 Andreas Klemenz (Fraunhofer IWM) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # This script demonstrates how to read an atomic configuration from an # extended xyz file and create input files for LAMMPS from it. # Alternatively, atomic configurations can be created directly in a # python script. See example 'atoms_to_lammps.py'. import matscipy.io.opls # Read the atomic configuration from an Extended XYZ file with labeled # atoms. The file should contain the following columns: element (1 or 2 # characters), x(float), y(float), z (float), molecule id (int), name # (1 or 2 characters). See the file "ethane.extxyz" for an example. # A full description of the extended xyz format can be found for example # in the ASE documentation. a = matscipy.io.opls.read_extended_xyz('ethane.extxyz') # To perform a non-reactive simulation, all types of pair, angle and # dihedral interactions must be specified manually. Usually this means # searching the literature for suitable parameters, which can be a # tedious task. If it is known which interactions are present in a # system, this can be much easier. Lists of all existing interactions # can be generated based on the distance of the atoms from each other. # The maximum distances up to which two atoms are considered to # interact can be read from a file. cutoffs = matscipy.io.opls.read_cutoffs('cutoffs.in') a.set_cutoffs(cutoffs) bond_types, _ = a.get_bonds() print('Pairwise interactions:') print(bond_types) angle_types, _ = a.get_angles() print('\nAngular interactions:') print(angle_types) dih_types, _ = a.get_dihedrals() print('\nDihedral interactions:') print(dih_types) # Once the parameters of all interactions are known, they can be written # to a file. This can be used to generate the lists of all interactions # and to create input files for LAMMPS. cutoffs, atom_data, bond_data, angle_data, dih_data = matscipy.io.opls.read_parameter_file('parameters.in') a.set_cutoffs(cutoffs) a.set_atom_data(atom_data) a.get_bonds(bond_data) a.get_angles(angle_data) a.get_dihedrals(dih_data) # Write the atomic structure, the potential definitions and a sample # input script for LAMMPS (3 files in total). The input script contains # a simple relaxation of the atomic position. Modify this file for more # complex simulations. matscipy.io.opls.write_lammps('example', a)
3,085
36.634146
107
py
matscipy
matscipy-master/examples/opls/atoms_to_lammps.py
#!/usr/bin/env python3 # # Copyright 2023 Andreas Klemenz (Fraunhofer IWM) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # This script demonstrates how to create an atomic configuration in a # python script and generate input files for LAMMPS from it. # Alternatively, atomic configurations can be read from an extended xyz # file. See example 'extxyz_to_lammps.py'. import numpy as np import ase import matscipy.opls import matscipy.io.opls # Simple example: ethane molecules # matscipy.opls.OPLSStructure is a subclass of ase.Atoms. OPLSStructure # objects can therefore be constructed and manipulated in the same way # as ase.Atoms objects a1 = matscipy.opls.OPLSStructure( 'C2H6', positions = [[1., 0., 0.], [2., 0., 0.], [0., 0., 0.], [1., 1., 0.], [1., -1., 0.], [2., 0., 1.], [2., 0., -1.], [3., 0., 0.]], cell = [10., 10., 10.] ) a1.translate([0., 3., 0.]) # Alternative: construct an ase.Atoms object and convert it to a # matscipy.opls.OPLSStructure object. a2 = ase.Atoms( 'C2H6', positions = [[1., 0., 0.], [2., 0., 0.], [0., 0., 0.], [1., 1., 0.], [1., -1., 0.], [2., 0., 1.], [2., 0., -1.], [3., 0., 0.]], cell = [10., 10., 10.] ) a2 = matscipy.opls.OPLSStructure(a2) a = matscipy.opls.OPLSStructure(cell=[10., 10., 10.]) a.extend(a1) a.extend(a2) a.center() # Specify atomic types. Notice the difference between type and element. # In this example we are using two different types of hydrogen atoms. a.set_types(['C1', 'C1', 'H1', 'H1', 'H1', 'H2', 'H2', 'H2', 'C1', 'C1', 'H1', 'H1', 'H1', 'H2', 'H2', 'H2']) # To perform a non-reactive simulation, all types of pair, angle and # dihedral interactions must be specified manually. Usually this means # searching the literature for suitable parameters, which can be a # tedious task. If it is known which interactions are present in a # system, this can be much easier. Lists of all existing interactions # can be generated based on the distance of the atoms from each other. # The maximum distances up to which two atoms are considered to interact # can be read from a file. cutoffs = matscipy.io.opls.read_cutoffs('cutoffs.in') a.set_cutoffs(cutoffs) bond_types, _ = a.get_bonds() print('Pairwise interactions:') print(bond_types) angle_types, _ = a.get_angles() print('\nAngular interactions:') print(angle_types) dih_types, _ = a.get_dihedrals() print('\nDihedral interactions:') print(dih_types) # Once the parameters of all interactions are known, they can be written # to a file. This can be used to generate the lists of all interactions # and to create input files for LAMMPS. cutoffs, atom_data, bond_data, angle_data, dih_data = matscipy.io.opls.read_parameter_file('parameters.in') a.set_cutoffs(cutoffs) a.set_atom_data(atom_data) a.get_bonds(bond_data) a.get_angles(angle_data) a.get_dihedrals(dih_data) # Write the atomic structure, the potential definitions and a sample # input script for LAMMPS (3 files in total). The input script contains # a simple relaxation of the atomic position. Modify this file for more # complex simulations. matscipy.io.opls.write_lammps('example', a)
4,090
32.260163
107
py
matscipy
matscipy-master/examples/electrochemistry/samples_stericify.py
# # Copyright 2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # %% [markdown] # # Steric correction # # *Johannes Hörmann, 2020* # # Impose steric radii on a sample point distribution by minizing pseudo-potential. # Pseudo-ptential follows formalism described in # # *L. Martinez, R. Andrade, E. G. Birgin, and J. M. Martínez, “PACKMOL: A package for building initial configurations for molecular dynamics simulations,” J. Comput. Chem., vol. 30, no. 13, pp. 2157–2164, 2009, doi: 10/chm6f7.* # # %% # for dynamic module reload during testing, code modifications take immediate effect # %load_ext autoreload # %autoreload 2 # %% # stretching notebook width across whole window from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) # %% # basics & utilities import itertools # dealing with combinations and permutations import logging # easy and neat handlin of log outpu import matplotlib.pyplot as plt # plotting import numpy as np # basic numerics, in particular lin. alg. import pandas as pd # display stats neatly import scipy.constants as sc # fundamental constants import scipy.spatial.distance # quick methods for computing pairwise distances import time # timing performance import timeit # same purpose # %% # electrochemistry basics from matscipy.electrochemistry import debye, ionic_strength # %% # Poisson-Bolzmann distribution from matscipy.electrochemistry.poisson_boltzmann_distribution import gamma, potential, concentration, charge_density # %% # sampling from scipy import interpolate from matscipy.electrochemistry import continuous2discrete from matscipy.electrochemistry import get_histogram from matscipy.electrochemistry.utility import plot_dist # %% # steric correction # target functions from matscipy.electrochemistry.steric_correction import scipy_distance_based_target_function from matscipy.electrochemistry.steric_correction import numpy_only_target_function from matscipy.electrochemistry.steric_correction import brute_force_target_function # closest pair functions from matscipy.electrochemistry.steric_correction import brute_force_closest_pair from matscipy.electrochemistry.steric_correction import planar_closest_pair from matscipy.electrochemistry.steric_correction import scipy_distance_based_closest_pair from matscipy.electrochemistry.steric_correction import apply_steric_correction # %% # 3rd party file output import ase import ase.io # %% # matscipy.electrochemistry makes extensive use of Python's logging module # configure logging: verbosity level and format as desired standard_loglevel = logging.INFO # standard_logformat = ''.join(("%(asctime)s", # "[ %(filename)s:%(lineno)s - %(funcName)s() ]: %(message)s")) standard_logformat = "[ %(filename)s:%(lineno)s - %(funcName)s() ]: %(message)s" # reset logger if previously loaded logging.shutdown() logging.basicConfig(level=standard_loglevel, format=standard_logformat, datefmt='%m-%d %H:%M') # in Jupyter notebooks, explicitly modifying the root logger necessary logger = logging.getLogger() logger.setLevel(standard_loglevel) # remove all handlers for h in logger.handlers: logger.removeHandler(h) # create and append custom handles ch = logging.StreamHandler() formatter = logging.Formatter(standard_logformat) ch.setFormatter(formatter) ch.setLevel(standard_loglevel) logger.addHandler(ch) # %% # Test 1 logging.info("Root logger") # %% # Test 2 logger.info("Root Logger") # %% # Debug Test logging.debug("Root logger") # %% [markdown] # ## Step 1: Solve for continuous concentration distributions # See other sample case notebboks for details # # %% # measures of box xsize = ysize = 5e-9 # nm, SI units zsize = 20e-9 # nm, SI units # get continuum distribution, z direction x = np.linspace(0, zsize, 2000) c = [1,1] z = [1,-1] u = 0.05 phi = potential(x, c, z, u) C = concentration(x, c, z, u) rho = charge_density(x, c, z, u) # %% # potential and concentration distributions analytic solution # based on Poisson-Boltzmann equation for 0.1 mM NaCl aqueous solution # at interface def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) for sp in ax.spines.values(): sp.set_visible(False) deb = debye(c, z) fig, ax1 = plt.subplots(figsize=[18,5]) ax1.set_xlabel('x (nm)') ax1.plot(x/sc.nano, phi, marker='', color='red', label='Potential', linewidth=1, linestyle='--') ax1.set_ylabel('potential (V)') ax1.axvline(x=deb/sc.nano, label='Debye Length', color='orange') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='Bulk concentration of Na+ ions', color='grey', linewidth=1, linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='green', label='Na+ ions') ax2.plot(x/sc.nano, C[1], marker='', color='blue', label='Cl- ions') ax2.set_ylabel('concentration (mM)') ax3 = ax1.twinx() # Offset the right spine of par2. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, par2 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density', color='grey', linewidth=1, linestyle='--') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') #fig.legend(loc='center') ax2.legend(loc='upper right', bbox_to_anchor=(-0.1, 1.02),fontsize=15) ax1.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1, -0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # ## Step 2: Sample from distribution # %% # create distribution functions distributions = [interpolate.interp1d(x,c) for c in C] # sample discrete coordinate set box3 = np.array([xsize, ysize, zsize]) sample_size = 200 # %% samples = [ continuous2discrete(distribution=d, box=box3, count=sample_size) for d in distributions ] species = ['Na+','Cl-'] for ion,sample,d in zip(species,samples,distributions): histx, histy, histz = get_histogram(sample, box=box3, n_bins=51) plot_dist(histx, 'Distribution of {:s} ions in x-direction'.format(ion), reference_distribution=lambda x: np.ones(x.shape)*1/box3[0]) plot_dist(histy, 'Distribution of {:s} ions in y-direction'.format(ion), reference_distribution=lambda x: np.ones(x.shape)*1/box3[1]) plot_dist(histz, 'Distribution of {:s} ions in z-direction'.format(ion), reference_distribution=d) # %% [markdown] # ## Step 3: Enforce steric radii # %% [markdown] # Initial state of system: # %% # need all coordinates in one N x 3 array xstacked = np.vstack(samples) box6 = np.array([[0.,0.,0],box3]) # needs lower corner n = xstacked.shape[0] dim = xstacked.shape[1] # benchmakr methods mindsq, (p1,p2) = scipy_distance_based_closest_pair(xstacked) pmin = np.min(xstacked,axis=0) pmax = np.max(xstacked,axis=0) mind = np.sqrt(mindsq) logger.info("Minimum pair-wise distance in sample: {}".format(mind)) logger.info("First sample point in pair: ({:8.4e},{:8.4e},{:8.4e})".format(*p1)) logger.info("Second sample point in pair ({:8.4e},{:8.4e},{:8.4e})".format(*p2)) logger.info("Box lower boundary: ({:8.4e},{:8.4e},{:8.4e})".format(*box6[0])) logger.info("Minimum coordinates in sample: ({:8.4e},{:8.4e},{:8.4e})".format(*pmin)) logger.info("Maximum coordinates in sample: ({:8.4e},{:8.4e},{:8.4e})".format(*pmax)) logger.info("Box upper boundary: ({:8.4e},{:8.4e},{:8.4e})".format(*box6[1])) # %% # apply penalty for steric overlap # stats: method, x, res, dt, mind, p1, p2 , pmin, pmax stats = [('initial',xstacked,None,0,mind,p1,p2,pmin,pmax)] r = 2e-10 # 4 Angstrom steric radius logger.info("Steric radius: {:8.4e}".format(r)) # see https://scipy-lectures.org/advanced/mathematical_optimization/index.html methods = [ #'Nelder-Mead', # not suitable 'Powell', 'CG', 'BFGS', #'Newton-CG', # needs explicit Jacobian 'L-BFGS-B' ] for m in methods: try: logger.info("### {} ###".format(m)) t0 = time.perf_counter() x1, res = apply_steric_correction(xstacked,box=box6,r=r,method=m) t1 = time.perf_counter() dt = t1 - t0 logger.info("{} s runtime".format(dt)) mindsq, (p1,p2) = scipy_distance_based_closest_pair(x1) mind = np.sqrt(mindsq) pmin = np.min(x1,axis=0) pmax = np.max(x1,axis=0) stats.append([m,x1,res,dt,mind,p1,p2,pmin,pmax]) logger.info("{:s} finished with".format(m)) logger.info(" status = {}, success = {}, #it = {}".format( res.status, res.success, res.nit)) logger.info(" message = '{}'".format(res.message)) logger.info("Minimum pair-wise distance in final configuration: {:8.4e}".format(mind)) logger.info("First sample point in pair: ({:8.4e},{:8.4e},{:8.4e})".format(*p1)) logger.info("Second sample point in pair ({:8.4e},{:8.4e},{:8.4e})".format(*p2)) logger.info("Box lower boundary: ({:8.4e},{:8.4e},{:8.4e})".format(*box6[0])) logger.info("Minimum coordinates in sample: ({:8.4e},{:8.4e},{:8.4e})".format(*pmin)) logger.info("Maximum coordinates in sample: ({:8.4e},{:8.4e},{:8.4e})".format(*pmax)) logger.info("Box upper boundary: ({:8.4e},{:8.4e},{:8.4e})".format(*box6[1])) except: logger.warning("{} failed.".format(m)) continue stats_df = pd.DataFrame( [ { 'method': s[0], 'runtime': s[3], 'mind': s[4], **{'p1{:d}'.format(i): c for i,c in enumerate(s[5]) }, **{'p2{:d}'.format(i): c for i,c in enumerate(s[6]) }, **{'pmin{:d}'.format(i): c for i,c in enumerate(s[7]) }, **{'pmax{:d}'.format(i): c for i,c in enumerate(s[8]) } } for s in stats] ) print(stats_df.to_string(float_format='%8.6g')) # %% [markdown] # L-BFGS-B fastest. # %% # Check difference between initial and final configuration, use last result (L-BFGS-B) np.count_nonzero(xstacked - x1) # that many coordinates modified # %% # Check difference between initial and final configuration, use last result (L-BFGS-B) np.linalg.norm(xstacked - x1) # euclidean distance between two sets # %% [markdown] # ## Step 4: Visualize results # %% # pick last result and split by species steric_samples = [ x1[:sample_size,:], x1[sample_size:,:] ] # %% nbins = 101 for ion,sample,d in zip(species,steric_samples,distributions): histx, histy, histz = get_histogram(sample, box=box3, n_bins=nbins) plot_dist(histx, 'Distribution of {:s} ions in x-direction'.format(ion), reference_distribution=lambda x: np.ones(x.shape)*1/box3[0]) plot_dist(histy, 'Distribution of {:s} ions in y-direction'.format(ion), reference_distribution=lambda x: np.ones(x.shape)*1/box3[1]) plot_dist(histz, 'Distribution of {:s} ions in z-direction'.format(ion), reference_distribution=d) # %% # Distribution of corrections for ion,sample,steric_sample,d in zip(species,samples,steric_samples,distributions): hists = get_histogram(sample, box=box3, n_bins=nbins) steric_hists = get_histogram(steric_sample, box=box3, n_bins=nbins) # first entry is counts, second entry is bins diff_hists = [ (h[0] - hs[0], h[1]) for h,hs in zip(hists,steric_hists) ] for ax, h in zip( ['x','y','z'], diff_hists ): plot_dist(h, 'Difference from non-steric to steric {:s} ion sample in {:s}-direction'.format(ion, ax)) # %% [markdown] # ## Step 5: Write to file # We utilize ASE to export it to some standard format, i.e. LAMMPS data file. # ASE speaks Ångström per default, thus we convert SI units: # %% symbols = ['Na','Cl'] # %% system = ase.Atoms( cell=np.diag(box3/sc.angstrom), pbc=[True,True,False]) for symbol, sample, charge in zip(symbols,samples,z): system += ase.Atoms( symbols=symbol*sample_size, charges=[charge]*sample_size, positions=sample/sc.angstrom) system # %% ase.io.write('NaCl_200_0.05V_5x5x20nm_at_interface_pb_distributed.lammps',system,format='lammps-data',units="real",atom_style='full') # %% steric_system = ase.Atoms( cell=np.diag(box3/sc.angstrom), pbc=[True,True,False]) for symbol, sample, charge in zip(symbols,steric_samples,z): steric_system += ase.Atoms( symbols=symbol*sample_size, charges=[charge]*sample_size, positions=sample/sc.angstrom) steric_system # %% ase.io.write('NaCl_200_0.05V_5x5x20nm_at_interface_pb_distributed_steric_correction_2Ang.lammps',steric_system,format='lammps-data',units="real",atom_style='full') # %% [markdown] # Displacement visualization between non-steric and steric sample with Ovito: # %% [markdown] # ![Steric correction on 200 NaCl](steric_correction_on_200_NaCl_300px.png) # %% [markdown] # ## Other performance tests # %% [markdown] # ### Comparing target function implementations # %% # prepare coordinates and get system dimensions xstacked = np.vstack(samples) n = xstacked.shape[0] dim = xstacked.shape[1] # normalize volume and coordinates V = np.product(box6[1]-box6[0]) L = np.power(V,(1./dim)) x0 = xstacked / L funcs = [ brute_force_target_function, numpy_only_target_function, scipy_distance_based_target_function ] func_names = ['brute','numpy','scipy'] # test for different scalings of coordinate set: stats = [] K = np.exp(np.log(10)*np.arange(-3,3)) for k in K: lambdas = [ (lambda x0=xstacked,k=k,f=f: f(x0*k)) for f in funcs ] vals = [ f() for f in lambdas ] times = [ timeit.timeit(f,number=1) for f in lambdas ] diffs = scipy.spatial.distance.pdist(np.atleast_2d(vals).T,metric='euclidean') stats.append((k,*vals,*diffs,*times)) func_name_tuples = list(itertools.combinations(func_names,2)) diff_names = [ 'd_{:s}_{:s}'.format(f1,f2) for (f1,f2) in func_name_tuples ] perf_names = [ 't_{:s}'.format(f) for f in func_names ] fields = ['k',*func_names,*diff_names,*perf_names] dtypes = [ (field, '>f4') for field in fields ] labeled_stats = np.array(stats,dtype=dtypes) stats_df = pd.DataFrame(labeled_stats) print(stats_df.to_string(float_format='%8.6g')) # %% [markdown] # Scipy-based target function fastest. # %% [markdown] # ### Comparing closest pair implementations # See https://www.researchgate.net/publication/266617010_NumPy_SciPy_Recipes_for_Data_Science_Squared_Euclidean_Distance_Matrices # %% # test minimum distance function implementations on random samples N = 1000 dim = 3 funcs = [ brute_force_closest_pair, scipy_distance_based_closest_pair, planar_closest_pair ] func_names = ['brute','scipy','planar'] stats = [] for k in range(5): x = np.random.rand(N,dim) lambdas = [ (lambda x=x,f=f: f(x)) for f in funcs ] rets = [ f() for f in lambdas ] vals = [ v[0] for v in rets ] coords = [ c for v in rets for p in v[1] for c in p ] times = [ timeit.timeit(f,number=1) for f in lambdas ] diffs = scipy.spatial.distance.pdist( np.atleast_2d(vals).T,metric='euclidean') stats.append((*vals,*diffs,*times,*coords)) func_name_tuples = list(itertools.combinations(func_names,2)) diff_names = [ 'd_{:s}_{:s}'.format(f1,f2) for (f1,f2) in func_name_tuples ] perf_names = [ 't_{:s}'.format(f) for f in func_names ] coord_names = [ 'p{:d}{:s}_{:s}'.format(i,a,f) for f in func_names for i in (1,2) for a in ('x','y','z') ] float_fields = [*func_names,*diff_names,*perf_names,*coord_names] dtypes = [ (field, 'f4') for field in float_fields ] labeled_stats = np.array(stats,dtype=dtypes) stats_df = pd.DataFrame(labeled_stats) print(stats_df.T.to_string(float_format='%8.6g')) # %% [markdown] # Scipy-based implementation fastest. # %% print('{}'.format(system.symbols)) # %% system.cell.array # %% np.array(system.get_cell_lengths_and_angles())
16,954
33.743852
227
py
matscipy
matscipy-master/examples/electrochemistry/samples_pnp_by_fenics_fem.py
# # Copyright 2020-2021 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # %% [markdown] # # Poisson-Nernst-Planck systems by finite element method # %% [markdown] # Johannes Laurin Hörmann, [email protected], [email protected], Nov 2020 # %% [markdown] # ## Initialization # %% # stretching notebook width across whole window from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) # %% # for dynamic module reload during testing, code modifications take immediate effect # %load_ext autoreload # %autoreload 2 # %% # %matplotlib inline # %% from IPython.core.display import display, HTML # %% # basics import logging import numpy as np import scipy.constants as sc import matplotlib.pyplot as plt # sampling # from scipy import interpolate # from matscipy.electrochemistry import continuous2discrete # from matscipy.electrochemistry import get_histogram # from matscipy.electrochemistry.utility import plot_dist # electrochemistry basics from matscipy.electrochemistry import debye, ionic_strength # Poisson-Bolzmann distribution from matscipy.electrochemistry.poisson_boltzmann_distribution import gamma, potential, concentration, charge_density # Poisson-Nernst-Planck solver from matscipy.electrochemistry import PoissonNernstPlanckSystem from matscipy.electrochemistry.poisson_nernst_planck_solver_fenics import PoissonNernstPlanckSystemFEniCS # from matscipy.electrochemistry.poisson_nernst_planck_solver_logc import PoissonNernstPlanckSystemLogC # 3rd party file output import ase import ase.io # %% def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) for sp in ax.spines.values(): sp.set_visible(False) # %% pnp = {} # %% [markdown] # # Convergence in both cases # %% # Test case parameters c=[1.0, 1.0] z=[ 1, -1] L=10e-8 # 200 nm delta_u=0.05 # V N=200 # %% # define desired system pnp['std_interface'] = PoissonNernstPlanckSystem( c, z, L, delta_u=delta_u,N=N, solver="hybr", options={'xtol':1e-12}) pnp['std_interface'].useStandardInterfaceBC() uij, nij, lamj = pnp['std_interface'].solve() # %% # define desired system pnp['fenics_interface'] = PoissonNernstPlanckSystemFEniCS(c, z, L, delta_u=delta_u,N=N) pnp['fenics_interface'].useStandardInterfaceBC() uij, nij, _ = pnp['fenics_interface'].solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot( pnp['fenics_interface'].grid/sc.nano, pnp['fenics_interface'].potential, marker='', color='tab:red', label='potential, PNP, FEM', linewidth=1, linestyle='-') ax1.plot( pnp['std_interface'].grid/sc.nano, pnp['std_interface'].potential, marker='', color='tab:red', label='potential, PNP', linewidth=2, linestyle='--') ax1.plot( x/sc.nano, phi, marker='', color='tab:red', label='potential, PB', linewidth=4, linestyle=':') ax2 = ax1.twinx() ax2.plot(pnp['fenics_interface'].grid/sc.nano, pnp['fenics_interface'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['std_interface'].grid/sc.nano, pnp['std_interface'].concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, C[0], marker='', color='tab:orange', label='Na+, PB', linewidth=4, linestyle=':') ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax2.plot(pnp['fenics_interface'].grid/sc.nano, pnp['fenics_interface'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['std_interface'].grid/sc.nano, pnp['std_interface'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB', linewidth=4, linestyle=':') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp['fenics_interface'].grid/sc.nano, pnp['fenics_interface'].charge_density, label='Charge density, PNP, FEM', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp['std_interface'].grid/sc.nano, pnp['std_interface'].charge_density, label='Charge density, PNP', color='grey', linewidth=2, linestyle='--') ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=4, linestyle=':') ax4.semilogy( pnp['fenics_interface'].grid/sc.nano, pnp['fenics_interface'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['std_interface'].grid/sc.nano, pnp['std_interface'].concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB', linewidth=4, linestyle=':') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax4.semilogy( pnp['fenics_interface'].grid/sc.nano, pnp['fenics_interface'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['std_interface'].grid/sc.nano, pnp['std_interface'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linewidth=4,linestyle=':') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper left', bbox_to_anchor=(1.3,1.02), fontsize=12, frameon=False) ax2.legend(loc='center left', bbox_to_anchor=(1.3,0.5), fontsize=12, frameon=False) ax3.legend(loc='lower left', bbox_to_anchor=(1.3,-0.02), fontsize=12, frameon=False) fig.tight_layout() plt.show() # %% [markdown] # # Convergence issues for CV # %% # Test case parameters oö c=[1.0, 1.0] z=[ 1, -1] L=10e-8 # 200 nm delta_u=0.2 # V N=200 # %% pnp['std_interface_high_potential'] = PoissonNernstPlanckSystem( c, z, L, delta_u=delta_u,N=N, solver="hybr", options={'xtol':1e-14}) pnp['std_interface_high_potential'].useStandardInterfaceBC() uij, nij, lamj = pnp['std_interface_high_potential'].solve() # %% pnp['fenics_interface_high_potential'] = PoissonNernstPlanckSystemFEniCS(c, z, L, delta_u=delta_u,N=200) pnp['fenics_interface_high_potential'].useStandardInterfaceBC() uij, nij, _ = pnp['fenics_interface_high_potential'].solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot( pnp['fenics_interface_high_potential'].grid/sc.nano, pnp['fenics_interface_high_potential'].potential, marker='', color='tab:red', label='potential, PNP, FEM', linewidth=1, linestyle='-') ax1.plot( pnp['std_interface_high_potential'].grid/sc.nano, pnp['std_interface_high_potential'].potential, marker='', color='tab:red', label='potential, PNP', linewidth=2, linestyle='--') ax1.plot( x/sc.nano, phi, marker='', color='tab:red', label='potential, PB', linewidth=4, linestyle=':') ax2 = ax1.twinx() ax2.plot(pnp['fenics_interface_high_potential'].grid/sc.nano, pnp['fenics_interface_high_potential'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['std_interface_high_potential'].grid/sc.nano, pnp['std_interface_high_potential'].concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, C[0], marker='', color='tab:orange', label='Na+, PB', linewidth=4, linestyle=':') ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax2.plot(pnp['fenics_interface_high_potential'].grid/sc.nano, pnp['fenics_interface_high_potential'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['std_interface_high_potential'].grid/sc.nano, pnp['std_interface_high_potential'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB', linewidth=4, linestyle=':') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp['fenics_interface_high_potential'].grid/sc.nano, pnp['fenics_interface_high_potential'].charge_density, label='Charge density, PNP, FEM', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp['std_interface_high_potential'].grid/sc.nano, pnp['std_interface_high_potential'].charge_density, label='Charge density, PNP', color='grey', linewidth=2, linestyle='--') ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=4, linestyle=':') ax4.semilogy( pnp['fenics_interface_high_potential'].grid/sc.nano, pnp['fenics_interface_high_potential'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['std_interface_high_potential'].grid/sc.nano, pnp['std_interface_high_potential'].concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB', linewidth=4, linestyle=':') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax4.semilogy( pnp['fenics_interface_high_potential'].grid/sc.nano, pnp['fenics_interface_high_potential'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['std_interface_high_potential'].grid/sc.nano, pnp['std_interface_high_potential'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linewidth=4,linestyle=':') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper left', bbox_to_anchor=(1.3,1.02), fontsize=12, frameon=False) ax2.legend(loc='center left', bbox_to_anchor=(1.3,0.5), fontsize=12, frameon=False) ax3.legend(loc='lower left', bbox_to_anchor=(1.3,-0.02), fontsize=12, frameon=False) fig.tight_layout() plt.show() # %% [markdown] # # Standard cell boundary conditions # %% c=[1000.0, 1000.0] z=[ 1, -1] L=20e-9 # 20 nm delta_u=0.8 # V # %% pnp['std_cell'] = PoissonNernstPlanckSystem( c, z, L, delta_u=delta_u, solver="hybr", options={'xtol':1e-15}) pnp['std_cell'].useStandardCellBC() uij, nij, lamj = pnp['std_cell'].solve() # %% pnp['fenics_cell'] = PoissonNernstPlanckSystemFEniCS( c, z, L, delta_u=delta_u) pnp['fenics_cell'].useStandardCellBC() uij, nij, lamj = pnp['fenics_cell'].solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot( pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].potential, marker='', color='tab:red', label='potential, PNP, FEM', linewidth=1, linestyle='-') ax1.plot( pnp['std_cell'].grid/sc.nano, pnp['std_cell'].potential, marker='', color='tab:red', label='potential, PNP', linewidth=2, linestyle='--') ax2 = ax1.twinx() ax2.plot(pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['std_cell'].grid/sc.nano, pnp['std_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax2.plot(pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['std_cell'].grid/sc.nano, pnp['std_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='--') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.2)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].charge_density, label='Charge density, PNP, FEM', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp['std_cell'].grid/sc.nano, pnp['std_cell'].charge_density, label='Charge density, PNP', color='grey', linewidth=2, linestyle='--') ax4.semilogy( pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['std_cell'].grid/sc.nano, pnp['std_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax4.semilogy( pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['std_cell'].grid/sc.nano, pnp['std_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='--') ax1.set_xlabel('z (nm)') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper left', bbox_to_anchor=(1.3,1.02), fontsize=12, frameon=False) ax2.legend(loc='center left', bbox_to_anchor=(1.3,0.5), fontsize=12, frameon=False) ax3.legend(loc='lower left', bbox_to_anchor=(1.3,-0.02), fontsize=12, frameon=False) fig.tight_layout() plt.show() # %% [markdown] # # Standard cell boundary conditions with initial values # %% delta_u=1.2 # V # %% pnp['fenics_cell_high_potential'] = PoissonNernstPlanckSystemFEniCS( c, z, L, delta_u=delta_u, potential0=pnp['fenics_cell'].potential, concentration0=pnp['fenics_cell'].concentration,N=1000) pnp['fenics_cell_high_potential'].useStandardCellBC() uij, nij, lamj = pnp['fenics_cell_high_potential'].solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot( pnp['fenics_cell_high_potential'].grid/sc.nano, pnp['fenics_cell_high_potential'].potential, marker='', color='tab:red', label='potential, PNP, FEM, u = 1.2 V', linewidth=1, linestyle='-') ax1.plot( pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].potential, marker='', color='tab:red', label='potential, PNP, FEM, u = 0.8 V', linewidth=2, linestyle='--') ax2 = ax1.twinx() ax2.plot(pnp['fenics_cell_high_potential'].grid/sc.nano, pnp['fenics_cell_high_potential'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, u = 1.2 V', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, u = 0.8 V', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax2.plot(pnp['fenics_cell_high_potential'].grid/sc.nano, pnp['fenics_cell_high_potential'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, u = 1.2 V', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, u = 0.8 V', linewidth=2, linestyle='--') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp['fenics_cell_high_potential'].grid/sc.nano, pnp['fenics_cell_high_potential'].charge_density, label='Charge density, PNP, FEM', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].charge_density, label='Charge density, PNP', color='grey', linewidth=2, linestyle='--') ax4.semilogy( pnp['fenics_cell_high_potential'].grid/sc.nano, pnp['fenics_cell_high_potential'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax4.semilogy( pnp['fenics_cell_high_potential'].grid/sc.nano, pnp['fenics_cell_high_potential'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='--') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper left', bbox_to_anchor=(1.3,1.02), fontsize=12, frameon=False) ax2.legend(loc='center left', bbox_to_anchor=(1.3,0.5), fontsize=12, frameon=False) ax3.legend(loc='lower left', bbox_to_anchor=(1.3,-0.02), fontsize=12, frameon=False) fig.tight_layout() plt.show() # %% plt.plot(pnp['fenics_cell'].concentration[0][0:100]) # %% plt.plot(pnp['fenics_cell_high_potential'].concentration[0][0:100]) # %% [markdown] # # Reference concentration cell boundary conditions # %% import fenics as fn # %% # Test case parameters c=[1000.0, 1000.0] z=[ 1, -1] L=20e-9 # 20 nm a=28e-9 # 28 x 28 nm area delta_u=0.2 # V # %% pnp['fenics_cell_low_potential'] = PoissonNernstPlanckSystemFEniCS( c, z, L, delta_u=delta_u, N = 200) pnp['fenics_cell_low_potential'].useStandardCellBC() uij, nij, lamj = pnp['fenics_cell_low_potential'].solve() # %% pnp['fenics_cell_c_ref'] = PoissonNernstPlanckSystemFEniCS( c, z, L, delta_u=delta_u, N = 300, potential0=pnp['fenics_cell_low_potential'].potential, concentration0=pnp['fenics_cell_low_potential'].concentration) pnp['fenics_cell_c_ref'].useCentralReferenceConcentrationBasedCellBC() uij, nij, lamj = pnp['fenics_cell_c_ref'].solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot( pnp['fenics_cell_low_potential'].grid/sc.nano, pnp['fenics_cell_low_potential'].potential, marker='', color='tab:red', label='potential, PNP, FEM', linewidth=1, linestyle='-') ax1.plot( pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].potential, marker='', color='tab:red', label='potential, PNP, FEM, central reference concentration', linewidth=2, linestyle='--') ax2 = ax1.twinx() ax2.plot(pnp['fenics_cell_low_potential'].grid/sc.nano, pnp['fenics_cell_low_potential'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, central reference concentration', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax2.plot(pnp['fenics_cell_low_potential'].grid/sc.nano, pnp['fenics_cell_low_potential'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, central reference concentration', linewidth=2, linestyle='--') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp['fenics_cell_low_potential'].grid/sc.nano, pnp['fenics_cell_low_potential'].charge_density, label='Charge density, PNP, FEM', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].charge_density, label='Charge density, PNP, FEM, central reference concentration', color='grey', linewidth=2, linestyle='--') ax4.semilogy( pnp['fenics_cell_low_potential'].grid/sc.nano, pnp['fenics_cell_low_potential'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, central reference concentration', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax4.semilogy( pnp['fenics_cell_low_potential'].grid/sc.nano, pnp['fenics_cell_low_potential'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, central reference concentration', linewidth=2, linestyle='--') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper left', bbox_to_anchor=(1.3,1.02), fontsize=12, frameon=False) ax2.legend(loc='center left', bbox_to_anchor=(1.3,0.5), fontsize=12, frameon=False) ax3.legend(loc='lower left', bbox_to_anchor=(1.3,-0.02), fontsize=12, frameon=False) fig.tight_layout() plt.show() # %% delta_u=0.4 # %% pnp['fenics_cell_c_ref_u_0.4'] = PoissonNernstPlanckSystemFEniCS( c, z, L, delta_u=delta_u, N=2000, potential0=pnp['fenics_cell_c_ref'].potential, concentration0=pnp['fenics_cell_c_ref'].concentration) pnp['fenics_cell_c_ref_u_0.4'].useCentralReferenceConcentrationBasedCellBC() uij, nij, lamj = pnp['fenics_cell_c_ref_u_0.4'].solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot( pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].potential, marker='', color='tab:red', label='potential, PNP, fenics', linewidth=1, linestyle='-') ax1.plot( pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].potential, marker='', color='tab:red', label='potential, PNP', linewidth=2, linestyle='--') ax2 = ax1.twinx() ax2.plot(pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax2.plot(pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='--') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].charge_density, label='Charge density, PNP, FEM', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].charge_density, label='Charge density, PNP', color='grey', linewidth=2, linestyle='--') ax4.semilogy( pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax4.semilogy( pnp['fenics_cell_c_ref'].grid/sc.nano, pnp['fenics_cell_c_ref'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='--') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper left', bbox_to_anchor=(1.3,1.02), fontsize=12, frameon=False) ax2.legend(loc='center left', bbox_to_anchor=(1.3,0.5), fontsize=12, frameon=False) ax3.legend(loc='lower left', bbox_to_anchor=(1.3,-0.02), fontsize=12, frameon=False) fig.tight_layout() plt.show() # %% delta_u=0.5 # %% pnp['fenics_cell_c_ref_u_0.6'] = PoissonNernstPlanckSystemFEniCS( c, z, L, delta_u=delta_u, N=6000, potential0=pnp['fenics_cell_c_ref_u_0.4'].potential, concentration0=pnp['fenics_cell_c_ref_u_0.4'].concentration) pnp['fenics_cell_c_ref_u_0.6'].useCentralReferenceConcentrationBasedCellBC() uij, nij, lamj = pnp['fenics_cell_c_ref_u_0.6'].solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[20,10]) ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot( pnp['fenics_cell_c_ref_u_0.6'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.6'].potential, marker='', color='tab:red', label='potential, PNP, FEM, central reference concentration, u = 0.5 V', linewidth=1, linestyle='-') ax1.plot( pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].potential, marker='', color='tab:red', label='potential, PNP, FEM, central reference concentration, u = 0.4 V', linewidth=2, linestyle='--') ax2 = ax1.twinx() ax2.plot(pnp['fenics_cell_c_ref_u_0.6'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.6'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, central reference concentration, u = 0.5 V', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, central reference concentration, u = 0.4 V', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax2.plot(pnp['fenics_cell_c_ref_u_0.6'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.6'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, central reference concentration, u = 0.5 V', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, central reference concentration, u = 0.4 V', linewidth=2, linestyle='--') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp['fenics_cell_c_ref_u_0.6'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.6'].charge_density, label='Charge density, PNP, FEM, central reference concentration, u = 0.5 V', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].charge_density, label='Charge density, PNP, FEM, central reference concentration, u = 0.4 V', color='grey', linewidth=2, linestyle='--') ax4.semilogy( pnp['fenics_cell_c_ref_u_0.6'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.6'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, central reference concentration, u = 0.5 V', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, central reference concentration, u = 0.4 V', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax4.semilogy( pnp['fenics_cell_c_ref_u_0.6'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.6'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, central reference concentration, u = 0.5 V', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_cell_c_ref_u_0.4'].grid/sc.nano, pnp['fenics_cell_c_ref_u_0.4'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, central reference concentration, u = 0.4 V', linewidth=2, linestyle='--') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper left', bbox_to_anchor=(1.3,1.02), fontsize=12, frameon=False) ax2.legend(loc='center left', bbox_to_anchor=(1.3,0.5), fontsize=12, frameon=False) ax3.legend(loc='lower left', bbox_to_anchor=(1.3,-0.02), fontsize=12, frameon=False) fig.tight_layout() plt.show() # %% plt.plot(pnp['fenics_cell_c_ref'].concentration[0]) # %% plt.plot(pnp['fenics_cell_c_ref'].concentration[1]) # %% [markdown] # # Stern layer cell boundary conditions # %% # Test case parameters oö c=[1000.0, 1000.0] z=[ 1, -1] L=20e-9 # 20 nm a=28e-9 # 28 x 28 nm area lambda_S=5e-11 # lambda_S=1 delta_u=0.8 # V # %% pnp['fenics_stern_layer_cell'] = PoissonNernstPlanckSystemFEniCS( c, z, L, delta_u=delta_u, N = 200, lambda_S=lambda_S) pnp['fenics_stern_layer_cell'].useSternLayerCellBC() uij, nij, lamj = pnp['fenics_stern_layer_cell'].solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[20,10]) ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot( pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].potential, marker='', color='tab:red', label='potential, PNP, FEM, Dirichlet BC on potential', linewidth=1, linestyle='-') ax1.plot( pnp['fenics_stern_layer_cell'].grid/sc.nano, pnp['fenics_stern_layer_cell'].potential, marker='', color='tab:red', label='potential, PNP, FEM, Robin BC on potential', linewidth=2, linestyle='--') ax2 = ax1.twinx() ax2.plot(pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, Dirichlet BC on potential', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_stern_layer_cell'].grid/sc.nano, pnp['fenics_stern_layer_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, Robin BC on potential', linewidth=2, linestyle='--') ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax2.plot(pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, Dirichlet BC on potential', linewidth=1, linestyle='-') ax2.plot(pnp['fenics_stern_layer_cell'].grid/sc.nano, pnp['fenics_stern_layer_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, Robin BC on potential', linewidth=2, linestyle='--') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.15)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].charge_density, label='Charge density, PNP, FEM, Dirichlet BC on potential', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp['fenics_stern_layer_cell'].grid/sc.nano, pnp['fenics_stern_layer_cell'].charge_density, label='Charge density, PNP, FEM, Robin BC on potential', color='grey', linewidth=2, linestyle='--') ax4.semilogy( pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, Dirichlet BC on potential', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_stern_layer_cell'].grid/sc.nano, pnp['fenics_stern_layer_cell'].concentration[0], marker='', color='tab:orange', label='Na+, PNP, FEM, Robin BC on potential', linewidth=2, linestyle='--') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linewidth=2, linestyle='-.') ax4.semilogy( pnp['fenics_cell'].grid/sc.nano, pnp['fenics_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, Dirichlet BC on potential', linewidth=1, linestyle='-') ax4.semilogy( pnp['fenics_stern_layer_cell'].grid/sc.nano, pnp['fenics_stern_layer_cell'].concentration[1], marker='', color='tab:blue', label='Cl-, PNP, FEM, Robin BC on potential', linewidth=2, linestyle='--') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper left', bbox_to_anchor=(1.3,1.02), fontsize=12, frameon=False) ax2.legend(loc='center left', bbox_to_anchor=(1.3,0.5), fontsize=12, frameon=False) ax3.legend(loc='lower left', bbox_to_anchor=(1.3,-0.02), fontsize=12, frameon=False) fig.tight_layout() plt.show()
40,123
41.776119
133
py
matscipy
matscipy-master/examples/electrochemistry/samples_pnp_c2d.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # %% [markdown] # # Poisson-Nernst-Planck systems & continuous2discrete # # *Johannes Hörmann, Lukas Elflein, 2019* # # from continuous electrochemical double layer theory to discrete coordinate sets # %% # for dynamic module reload during testing, code modifications take immediate effect # %load_ext autoreload # %autoreload 2 # %% # stretching notebook width across whole window from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) # %% # basics import logging import numpy as np import scipy.constants as sc import matplotlib.pyplot as plt # %% # sampling from scipy import interpolate from matscipy.electrochemistry import continuous2discrete from matscipy.electrochemistry import get_histogram from matscipy.electrochemistry.utility import plot_dist # %% # electrochemistry basics from matscipy.electrochemistry import debye, ionic_strength # %% # Poisson-Bolzmann distribution from matscipy.electrochemistry.poisson_boltzmann_distribution import gamma, potential, concentration, charge_density # %% # Poisson-Nernst-Planck solver from matscipy.electrochemistry import PoissonNernstPlanckSystem # %% # 3rd party file output import ase import ase.io # %% # PoissonNernstPlanckSystem makes extensive use of Python's logging module # configure logging: verbosity level and format as desired standard_loglevel = logging.INFO # standard_logformat = ''.join(("%(asctime)s", # "[ %(filename)s:%(lineno)s - %(funcName)s() ]: %(message)s")) standard_logformat = "[ %(filename)s:%(lineno)s - %(funcName)s() ]: %(message)s" # reset logger if previously loaded logging.shutdown() logging.basicConfig(level=standard_loglevel, format=standard_logformat, datefmt='%m-%d %H:%M') # in Jupyter notebooks, explicitly modifying the root logger necessary logger = logging.getLogger() logger.setLevel(standard_loglevel) # remove all handlers for h in logger.handlers: logger.removeHandler(h) # create and append custom handles ch = logging.StreamHandler() formatter = logging.Formatter(standard_logformat) ch.setFormatter(formatter) ch.setLevel(standard_loglevel) logger.addHandler(ch) # %% # Test 1 logging.info("Root logger") # %% # Test 2 logger.info("Root Logger") # %% # Debug Test logging.debug("Root logger") # %% # tiny helper for plotting def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) for sp in ax.spines.values(): sp.set_visible(False) # %% [markdown] # # General Poisson-Nernst-Planck System # %% [markdown] # For general systems, i.e. a nanogap between two electrodes with not necessarily binary electrolyte, no closed analytic solution exists. # Thus, we solve the full Poisson-Nernst-Planck system of equations. # %% [markdown] # A binary Poisson-Nernst-Planck system corresponds to the transport problem in semiconductor physics. # In this context, Debye length, charge carrier densities and potential are related as follows. # %% [markdown] # ## Excursus: Transport problem in PNP junction (German) # %% [markdown] # ### Debye length # %% [markdown] # Woher kommt die Debye-Länge # # $$ \lambda = \sqrt{ \frac{\varepsilon \varepsilon_0 k_B T}{q^2 n_i} }$$ # # als natürliche Längeneinheit des Transportptoblems? # # Hier ist $n_i$ eine Referenzladungsträgerdichte, in der Regel die intrinsische Ladungsträgerdichte. # In dem Beispiel mit $N^+NN^+$-dotiertem Halbleiter erzeugen wir durch unterschiedliches Doping an den Rändern die erhöhte Donatorendichte $N_D^+ = 10^{20} \mathrm{cm}^{-3}$ und im mitteleren Bereich "Standarddonatorendichte" $N_D = 10^{18} \mathrm{cm}^{-3}$. Nun können wir als Referenz $n_i = N_D$ wählen und die Donatorendichten als $N_D = 1 \cdot n_i$ und $N_D^+ = 100 \cdot n_i$ ausdrücken. Diese normierte Konzentration nennen wir einfach $\tilde{N}_D$: $N_D = \tilde{N}_D \cdot n_i$. # # Ein ionisierter Donator trägt die Ladung $q$, ein Ladungsträger (in unserem Fall ein Elektron) trägt die Elementarladung $-q$. Die Raumladungsdichte $\rho$ in der Poissongleichung # # $$ \nabla^2 \varphi = - \frac{\rho}{\varepsilon \varepsilon_0}$$ # # lässt sich also ganz einfach als $\rho = - (n - N_D) \cdot q = - (\tilde{n} - \tilde{N}_D) ~ n_i ~ q$ ausdrücken. # # Konventionell wird das Potential auf $u = \frac{\phi ~ q}{k_B ~ T}$ normiert. Die Poissongleichung nimmt damit die Form # # $$\frac{k_B ~ T}{q} \cdot \nabla^2 u = \frac{(\tilde{n} - \tilde{N}_D) ~ n_i ~ q }{\varepsilon \varepsilon_0}$$ # # oder auch # # $$ \frac{\varepsilon ~ \varepsilon_0 ~ k_B ~ T}{q^2 n_i} \cdot \nabla^2 u = \lambda^2 \cdot \nabla^2 u = \tilde{n} - \tilde{N}_D$$ # # # %% [markdown] # ### Dimensionless formulation # %% [markdown] # Poisson- und Drift-Diffusionsgleichung # # $$ # \lambda^2 \frac{\partial^2 u}{\partial x^2} = n - N_D # $$ # # $$ # \frac{\partial n}{\partial t} = - D_n \ \frac{\partial}{\partial x} \left( n \ \frac{\partial u}{\partial x} - \frac{\partial n}{\partial x} \right) + R # $$ # # Skaliert mit [l], [t]: # # $$ # \frac{\lambda^2}{[l]^2} \frac{\partial^2 u}{\partial \tilde{x}^2} = n - N # $$ # # und # # $$ # \frac{1}{[t]} \frac{\partial n}{\partial \tilde{t}} = - \frac{D_n}{[l]^2} \ \frac{\partial}{\partial x} \left( n \ \frac{\partial u}{\partial x} - \frac{\partial n}{\partial x} \right) + R # $$ # # oder # # $$ # \frac{\partial n}{\partial \tilde{t}} = - \tilde{D}_n \ \frac{\partial}{\partial x} \left( n \ \frac{\partial u}{\partial x} - \frac{\partial n}{\partial x} \right) + \tilde{R} # $$ # # mit # # $$ # \tilde{D}_n = D_n \frac{[t]}{[l]^2} \Leftrightarrow [t] = [l]^2 \ \frac{ \tilde{D}_n } { D_n } # $$ # # und # # $$ \tilde{R} = \frac{n - N_D}{\tilde{\tau}}$$ # # mit $\tilde{\tau} = \tau / [t]$. # # $\tilde{\lambda} = 1$ und $\tilde{D_n} = 1$ werden mit # $[l] = \lambda$ und $[t] = \frac{\lambda^2}{D_n}$ erreicht: # %% [markdown] # ### Discretization # %% [markdown] # Naive Diskretisierung (skaliert): # # $$ \frac{1}{\Delta x^2} ( u_{i+1}-2u_i+u_{i-1} ) = n_i - N_i $$ # # $$ \frac{1}{\Delta t} ( n_{i,j+1} - n_{i,j} ) = - \frac{1}{\Delta x^2} \cdot \left[ \frac{1}{4} (n_{i+1} - n_{i-1}) (u_{i+1} - u_{i-1}) + n_i ( u_{i+1} - 2 u_i + u_{i-1} ) - ( n_{i+1} - 2 n_i + n_{i-1} ) \right] + \frac{ n_i - N_i}{ \tilde{\tau} } $$ # # Stationär: # # $$ # u_{i+1}-2u_i+u_{i-1} - \Delta x^2 \cdot n_i + \Delta x^2 \cdot N_i = 0 # $$ # # und # # $$ # \frac{1}{4} (n_{i+1} - n_{i-1}) (u_{i+1} - u_{i-1}) + n_i ( u_{i+1} - 2 u_i + u_{i-1} ) - ( n_{i+1} - 2 n_i + n_{i-1} ) - \Delta x^2 \cdot \frac{ n_i - N_i}{ \tilde{\tau} } = 0 # $$ # %% [markdown] # ### Newton-Iteration für gekoppeltes nicht-lineares Gleichungssystem # %% [markdown] # Idee: Löse nicht-lineares Finite-Differenzen-Gleichungssystem über Newton-Verfahren # # $$ \vec{F}(\vec{x}_{k+1}) = F(\vec{x}_k + \Delta \vec{x}_k) \approx F(\vec{x}_k) + \mathbf{J_F}(\vec{x}_k) \cdot \Delta \vec{x}_k + \mathcal{O}(\Delta x^2)$$ # # mit Unbekannter $\vec{x_k} = \{u_1^k, \dots, u_N^k, n_1^k, \dots, n_N^k\}$ und damit # # $$ \Rightarrow \Delta \vec{x}_k = - \mathbf{J}_F^{-1} ~ F(\vec{x}_k)$$ # # wobei die Jacobi-Matrix $2N \times 2N$ Einträge # # $$ \mathbf{J}_{ij}(\vec{x}_k) = \frac{\partial F_i}{\partial x_j} (\vec{x}_k) $$ # # besitzt, die bei jedem Iterationsschritt für $\vec{x}_k$ ausgewertet werden. # Der tatsächliche Aufwand liegt in der Invertierung der Jacobi-Matrix, um in jeder Iteration $k$ den Korrekturschritt $\Delta \vec{x}_k$ zu finden.m # %% [markdown] # $F(x)$ wird wie unten definiert als: # # $$ # u_{i+1}-2u_i+u_{i-1} - \Delta x^2 \cdot n_i + \Delta x^2 \cdot N_i = 0 # $$ # # und # # $$ # \frac{1}{4} (n_{i+1} - n_{i-1}) (u_{i+1} - u_{i-1}) + n_i ( u_{i+1} - 2 u_i + u_{i-1} ) - ( n_{i+1} - 2 n_i + n_{i-1} ) - \Delta x^2 \cdot \frac{ n_i - N_i}{ \tilde{\tau} } = 0 # $$ # %% [markdown] # ### Controlled-Volume # %% [markdown] # Drücke nicht-linearen Teil der Transportgleichung (genauer, des Flusses) über Bernoulli-Funktionen # # $$ B(x) = \frac{x}{\exp(x)-1} $$ # # aus (siehe Vorlesungsskript). Damit wir in der Nähe von 0 nicht "in die Bredouille geraten", verwenden wir hier lieber die Taylorentwicklung. In der Literatur (Selbherr, S. Analysis and Simulation of Semiconductor Devices, Spriger 1984) wird eine noch aufwendigere stückweise Definition empfohlen, allerdings werden wir im Folgenden sehen, dass unser Ansatz für dieses stationäre Problem genügt. # # %% [markdown] # ## Implementation for Poisson-Nernst-Planck system # %% [markdown] # Poisson-Nernst-Planck system for $k = {1 \dots M}$ ion species in dimensionless formulation # # $$ \nabla^2 u + \rho(n_{1},\dots,n_{M}) = 0 $$ # # $$ \nabla^2 n_k + \nabla ( z_k n_k \nabla u ) = 0 \quad \text{for} \quad k = 1 \dots M $$ # # yields a naive finite difference discretization on $i = {1 \dots N}$ grid points for $k = {1 \dots M}$ ion species # # $$ \frac{1}{\Delta x^2} ( u_{i+1}-2u_i+u_{i-1} ) + \frac{1}{2} \sum_{k=1}^M z_k n_{i,k} = 0 $$ # # $$ - \frac{1}{\Delta x^2} \cdot \left[ \frac{1}{4} z_k (n_{i+1,k} - n_{i-1,k}) (u_{i+1} - u_{i-1}) + z_k n_{i,k} ( u_{i+1} - 2 u_i + u_{i-1} ) + ( n_{i+1,k} - 2 n_{i,k} + n_{i-1,k} ) \right] $$ # # or rearranged # # $$ u_{i+1}-2 u_i+u_{i-1} + \Delta x^2 \frac{1}{2} \sum_{k=1}^M z_k n_{i,k} = 0 $$ # # and # # $$ # \frac{1}{4} z_k (n_{i+1,k} - n_{i-1,k}) (u_{i+1,k} - u_{i-1,k}) + z_k n_{i,k} ( u_{i+1} - 2 u_i + u_{i-1} ) - ( n_{i+1,k} - 2 n_{i,k} + n_{i-1,k} ) = 0 # $$ # %% [markdown] # ### Controlled Volumes, 1D # %% [markdown] # Finite differences do not converge in our non-linear systems. Instead, we express non-linear part of the Nernts-Planck equations with Bernoulli function (Selberherr, S. Analysis and Simulation of Semiconductor Devices, Spriger 1984) # # $$ B(x) = \frac{x}{\exp(x)-1} $$ # %% def B(x): return np.where( np.abs(x) < 1e-9, 1 - x/2 + x**2/12 - x**4/720, # Taylor x / ( np.exp(x) - 1 ) ) # %% xB = np.arange(-10,10,0.1) # %% plt.plot( xB ,B( xB ), label="$B(x)$") plt.plot( xB, - B(-xB), label="$-B(-x)$") plt.plot( xB, B(xB)-B(-xB), label="$B(x)-B(-x)$") plt.legend() # %% [markdown] # Looking at (dimensionless) flux $j_k$ throgh segment $k$ in between grid points $i$ and $j$, # # $$ j_k = - \frac{dn}{dx} - z n \frac{du}{dx} $$ # # for an ion species with number charge $z$ and (dimensionless) concentration $n$, # we assume (dimensionless) potential $u$ to behave linearly within this segment. The linear expression # # $$ u = \frac{u_j - u_i}{L_k} \cdot \xi_k + u_i = a_k \xi_k + u_i $$ # # with the segment's length $L_k = \Delta x$ for uniform discretization, $\xi_k = x - x_i$ and proportionality factor $a_k = \frac{u_j - u_i}{L_k}$ leadsd to a flux # # $$ j_k = - \frac{dn}{d\xi} - z a_k n $$ # # solvable for $v$ via # # $$ \frac{dn}{d\xi} = - z a_k n - j_k $$ # # or # # $$ \frac{dn}{z a_k n + j_k} = - d\xi \text{.} $$ # # We intergate from grid point $i$ to $j$ # # $$ \int_{n_i}^{n_j} \frac{1}{z a_k n + j_k} dn = - L_k $$ # # and find # # $$ \frac{1}{(z a_k)} \left[ \ln(j_k + z a_k n) \right]_{n_i}^{n^j} = - L_k $$ # # or # # $$ \ln(j_k + z a_k n_j) - \ln(j_k + z a_k n_i) = - z a_k L_k $$ # # which we solve for $j_k$ by rearranging # # $$ \frac{j_k + z a_k n_j}{j_k + z a_k n_i} = e^{- z a_k L_k} $$ # # $$ j_k + z a_k n_j = (j_k + z a_k n_i) e^{- z a_k L_k} $$ # # $$ j_k ( 1 - e^{- z a_k L_k} ) = - z a_k n_j + z a_k n_i e^{- z a_k L_k} $$ # # $$j_k = \frac{z a_k n_j}{e^{- z a_k L_k} - 1} + \frac{ z a_k n_i e^{- z a_k L_k}}{ 1 - e^{- z a_k L_k}}$$ # # $$j_k = \frac{1}{L_k} \cdot \left[ \frac{z a_k L_k n_j}{e^{- z a_k L_k} - 1} + \frac{ z a_k L_k n_i }{ e^{z a_k L_k} - 1} \right] $$ # # or with $B(x) = \frac{x}{e^x-1}$ expressed as # # $$j_k = \frac{1}{L_k} \cdot \left[ - n_j B( - z a_k L_k ) + n_i B( z a_k L_k) \right] $$ # # and resubstituting $a_k = \frac{u_j - u_i}{L_k}$ as # # $$j_k = - \frac{1}{L_k} \cdot \left[ n_j B( z [u_i - u_j] ) - n_i B( z [u_j - u_i] ) \right] \ \text{.}$$ # # When employing our 1D uniform grid with $j_k = j_{k-1}$ for all $k = 1 \dots N$, # # $$ j_k \Delta x = n_{i+1} B( z [u_i - u_{i+1}] ) - n_i B( z [u_{i+1} - u_i] ) $$ # # and # # $$ j_{k-1} \Delta x = n_i B( z [u_{i-1} - u_i] ) - n_{i-1} B( z [u_i - u_{i-1}] ) $$ # # require # # $$ n_{i+1} B( z [u_i - u_{i+1}] ) - n_i \left( B( z [u_{i+1} - u_i] ) + B( z [u_{i-1} - u_i] ) \right) + n_{i-1} B( z [u_i - u_{i-1}] ) = 0 $$ # %% [markdown] # ## Test case 1: PNP interface system, 0.1 mM NaCl, positive potential u = 0.05 V # %% # Test case parameters c=[0.1, 0.1] z=[ 1, -1] L=1e-07 delta_u=0.05 # %% # define desired system pnp = PoissonNernstPlanckSystem(c, z, L, delta_u=delta_u) # constructor takes keyword arguments # c=array([0.1, 0.1]), z=array([ 1, -1]), L=1e-07, T=298.15, delta_u=0.05, relative_permittivity=79, vacuum_permittivity=8.854187817620389e-12, R=8.3144598, F=96485.33289 # with default values set for 0.1 mM NaCl aqueous solution across 100 nm and 0.05 V potential drop # %% pnp.useStandardInterfaceBC() # %% pnp.output = True # let's Newton solver display convergence plots uij, nij, lamj = pnp.solve() # %% [markdown] # ### Validation: Analytical half-space solution & Numerical finite-size PNP system # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax1.plot(x/sc.nano, phi, marker='', color='tomato', label='potential, PB', linewidth=1, linestyle='--') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='Charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interface and at open right hand side # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interface and at open right hand side # %% (pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Cation concentration at interface and at open right hand side # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interface and at open right hand side # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # ## Test case 2: PNP interface system, 0.1 mM NaCl, negative potential u = -0.05 V, analytical solution as initial values # %% # Test case parameters c=[0.1, 0.1] z=[ 1, -1] L=1e-07 delta_u=-0.05 # %% pnp = PoissonNernstPlanckSystem(c, z, L, delta_u=delta_u) # %% pnp.useStandardInterfaceBC() # %% # initial config x = np.linspace(0, pnp.L, pnp.Ni) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) # %% pnp.ni0 = C / pnp.c_unit # manually remove dimensions from analyatical solution # %% ui0 = pnp.initial_values() # %% plt.plot(ui0) # solution to linear Poisson equation under assumption of fixed charge density distribution # %% pnp.output = True # let's Newton solver display convergence plots uij, nij, lamj = pnp.solve() # no faster convergence than above, compare convergence plots for test case 1 # %% [markdown] # ### Validation: Analytical half-space solution & Numerical finite-size PNP system # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax1.plot(x/sc.nano, phi, marker='', color='tomato', label='potential, PB', linewidth=1, linestyle='--') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='Charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interface and at open right hand side # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interface and at open right hand side # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,1) ) # %% [markdown] # #### Cation concentration at interface and at open right hand side # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interface and at open right hand side # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # ## Test case 3: PNP interface system, 0.1 mM NaCl, positive potential u = 0.05 V, 200 nm domain # %% # Test case parameters c=[0.1, 0.1] z=[ 1, -1] L=2e-07 delta_u=0.05 # %% pnp = PoissonNernstPlanckSystem(c, z, L, delta_u=delta_u) # %% pnp.useStandardInterfaceBC() # %% pnp.output = True uij, nij, lamj = pnp.solve() # %% [markdown] # ### Validation: Analytical half-space solution & Numerical finite-size PNP system # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax1.plot(x/sc.nano, phi, marker='', color='tomato', label='potential, PB', linewidth=1, linestyle='--') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='Charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # Analytic PB and approximate PNP solution indistinguishable. # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interface and at open right hand side # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interface and at open right hand side # %% (pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Cation concentration at interface and at open right hand side # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interface and at open right hand side # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # ## Test case 4: 1D electrochemical cell, 0.1 mM NaCl, positive potential u = 0.05 V, 100 nm domain # %% # Test case parameters c=[0.1, 0.1] z=[ 1, -1] L=1e-07 delta_u=0.05 # %% pnp = PoissonNernstPlanckSystem(c, z, L, delta_u=delta_u) # %% pnp.useStandardCellBC() # %% pnp.output = True xij = pnp.solve() # %% [markdown] # ### Validation: Analytical half-space solution & Numerical finite-size PNP system # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax1.plot(x/sc.nano, phi, marker='', color='tomato', label='potential, PB', linewidth=1, linestyle='--') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='Charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.set_xlabel('z [nm]') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_xlabel('z [nm]') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interfaces # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interfaces # %% (pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Cation concentration at interfaces # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interfaces # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # #### Equilibrium cation and anion amount # %% ( pnp.numberConservationConstraint(pnp.xij1,0,0), pnp.numberConservationConstraint(pnp.xij1,1,0) ) # %% [markdown] # #### Initial cation and anion amount # %% ( pnp.numberConservationConstraint(pnp.xi0,0,0), pnp.numberConservationConstraint(pnp.xi0,1,0) ) # %% [markdown] # #### Species conservation # %% (pnp.numberConservationConstraint(pnp.xij1,0, pnp.numberConservationConstraint(pnp.xi0,0,0)), pnp.numberConservationConstraint(pnp.xij1,1, pnp.numberConservationConstraint(pnp.xi0,1,0)) ) # %% [markdown] # ## Test case 5: 1D electrochemical cell, 0.1 mM NaCl, positive potential u = 0.05 V, 100 nm domain, 0.5 nm compact layer # %% [markdown] # At high potentials or bulk concentrations, pure PNP systems yield unphysically high concentrations and steep gradients close to the boundary, as an ion's finite size is not accounted for. # In addition, high gradients can lead to convergence issues. This problem can be alleviated by assuming a Stern layer (compact layer) at the interface. # This compact layer is parametrized by its thickness $\lambda_S$ and can be treated explicitly by prescribing a linear potential regime across the compact layer region, or by # the implicit parametrization of a compact layer with uniform charge density as Robin boundary conditions on the potential. # %% c = [1000,1000] # high concentrations close to NaCl's solubility limit in water delta_u = 0.05 L = 30e-10 # tiny gap of 3 nm lambda_S = 5e-10 # 0.5 nm Stern layer # %% pnp_no_compact_layer = PoissonNernstPlanckSystem(c,z,L,delta_u=delta_u, e=1e-12) # %% pnp_with_explicit_compact_layer = PoissonNernstPlanckSystem(c,z,L, delta_u=delta_u,lambda_S=lambda_S, e=1e-12) # %% pnp_with_implicit_compact_layer = PoissonNernstPlanckSystem(c,z,L, delta_u=delta_u,lambda_S=lambda_S, e=1e-12) # %% pnp_no_compact_layer.useStandardCellBC() # %% pnp_with_explicit_compact_layer.useSternLayerCellBC(implicit=False) # %% pnp_with_implicit_compact_layer.useSternLayerCellBC(implicit=True) # %% pnp_no_compact_layer.output = True xij_no_compact_layer = pnp_no_compact_layer.solve() # %% pnp_with_explicit_compact_layer.output = True xij_with_explicit_compact_layer = pnp_with_explicit_compact_layer.solve() # %% pnp_with_implicit_compact_layer.output = True xij_with_implicit_compact_layer = pnp_with_implicit_compact_layer.solve() # %% x = np.linspace(0,L,100) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[18,10]) # 1 - potentials ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.potential, marker='', color='tab:red', label='potential, without compact layer', linewidth=1, linestyle='-') ax1.plot(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.potential, marker='', color='tab:red', label='potential, with explicit compact layer', linewidth=1, linestyle='--') ax1.plot(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.potential, marker='', color='tab:red', label='potential, with Robin BC', linewidth=2, linestyle=':') # 2 - conencentratiosn ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax2.plot(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, without compact layer', linewidth=2, linestyle='-') ax2.plot(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, without compact layer', linewidth=2, linestyle='-') ax2.plot(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, with explicit compact layer', linewidth=2, linestyle='--') ax2.plot(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, with explicit compact layer', linewidth=2, linestyle='--') ax2.plot(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, with Robin BC', linewidth=2, linestyle=':') ax2.plot(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, with Robin BC', linewidth=2, linestyle=':') # 3 - charge densities ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.charge_density, label='charge density, without compact layer', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.charge_density, label='charge density, with explicit compact layer', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.charge_density, label='charge density, with Robin BC', color='grey', linewidth=1, linestyle=':') # 4 - concentrations, semi log ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax4.semilogy(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, without compact layer', linewidth=2, linestyle='-') ax4.semilogy(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, without compact layer', linewidth=2, linestyle='-') ax4.semilogy(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, with explicit compact layer', linewidth=2, linestyle='--') ax4.semilogy(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, with explicit compact layer', linewidth=2, linestyle='--') ax4.semilogy(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, with Robin BC', linewidth=2, linestyle=':') ax4.semilogy(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, with Robin BC', linewidth=2, linestyle=':') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') #ax3.yaxis.set_major_formatter(formatter) ax3.ticklabel_format(axis='y', style='sci', scilimits=(-2,10), useOffset=False, useMathText=False) ax4.set_xlabel('z [nm]') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=12) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=12) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=12) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # # (pnp_no_compact_layer.potential[0],pnp_no_compact_layer.potential[-1]) # # (pnp_with_explicit_compact_layer.potential[0],pnp_with_explicit_compact_layer.potential[-1]) # # (pnp_with_implicit_compact_layer.potential[0],pnp_with_implicit_compact_layer.potential[-1]) # # #### Residual cation flux at interfaces # # ( pnp_no_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_no_compact_layer.xij1,0), pnp_no_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_no_compact_layer.xij1,0) ) # # ( pnp_with_explicit_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_with_explicit_compact_layer.xij1,0), pnp_with_explicit_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_with_explicit_compact_layer.xij1,0) ) # # ( pnp_with_implicit_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_with_implicit_compact_layer.xij1,0), pnp_with_implicit_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_with_implicit_compact_layer.xij1,0) ) # # #### Residual cation flux at interfaces # # ( pnp_no_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_no_compact_layer.xij1,1), pnp_no_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_no_compact_layer.xij1,1) ) # # ( pnp_with_explicit_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_with_explicit_compact_layer.xij1,1), pnp_with_explicit_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_with_explicit_compact_layer.xij1,1) ) # # ( pnp_with_implicit_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_with_implicit_compact_layer.xij1,1), pnp_with_implicit_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_with_implicit_compact_layer.xij1,1) ) # # #### Cation concentration at interfaces # # (pnp_no_compact_layer.concentration[0,0],pnp_no_compact_layer.concentration[0,-1]) # # (pnp_with_explicit_compact_layer.concentration[0,0],pnp_with_explicit_compact_layer.concentration[0,-1]) # # (pnp_with_implicit_compact_layer.concentration[0,0],pnp_with_implicit_compact_layer.concentration[0,-1]) # # #### Anion concentration at interfaces # L # (pnp_no_compact_layer.concentration[1,0],pnp_no_compact_layer.concentration[1,-1]) # # (pnp_with_explicit_compact_layer.concentration[1,0],pnp_with_explicit_compact_layer.concentration[1,-1]) # # (pnp_with_implicit_compact_layer.concentration[1,0],pnp_with_implicit_compact_layer.concentration[1,-1]) # # #### Equilibrium cation and anion amount # # ( pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xij1,0,0), pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xij1,1,0) ) # # ( pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xij1,0,0), pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xij1,1,0) ) # # ( pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xij1,0,0), pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xij1,1,0) ) # # #### Initial cation and anion amount # # ( pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xi0,0,0), pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xi0,1,0) ) # # ( pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xi0,0,0), pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xi0,1,0) ) # # ( pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xi0,0,0), pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xi0,1,0) ) # # #### Species conservation # # (pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xij1,0, # pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xi0,0,0)), # pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xij1,1, # pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xi0,1,0)) ) # # (pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xij1,0, # pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xi0,0,0)), # pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xij1,1, # pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xi0,1,0)) ) # # (pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xij1,0, # pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xi0,0,0)), # pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xij1,1, # pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xi0,1,0)) ) # %% [markdown] # ## Sample application of 1D electrochemical cell model: # %% [markdown] # We want to fill a gap of 3 nm between gold electrodes with 0.2 wt % NaCl aqueous solution, apply a small potential difference and generate an initial configuration for LAMMPS within a cubic box: # %% box_Ang=np.array([50.,50.,50.]) # Angstrom # %% box_m = box_Ang*sc.angstrom # %% box_m # %% vol_AngCube = box_Ang.prod() # Angstrom^3 # %% vol_mCube = vol_AngCube*sc.angstrom**3 # %% [markdown] # With a concentration of 0.2 wt %, we are close to NaCl's solubility limit in water. # We estimate molar concentrations and atom numbers in our box: # %% # enter number between 0 ... 0.2 weight_concentration_NaCl = 0.2 # wt % # calculate saline mass density g/cm³ saline_mass_density_kg_per_L = 1 + weight_concentration_NaCl * 0.15 / 0.20 # g / cm^3, kg / L # see https://www.engineeringtoolbox.com/density-aqueous-solution-inorganic-sodium-salt-concentration-d_1957.html # %% saline_mass_density_g_per_L = saline_mass_density_kg_per_L*sc.kilo # %% molar_mass_H2O = 18.015 # g / mol molar_mass_NaCl = 58.44 # g / mol # %% cNaCl_M = weight_concentration_NaCl*saline_mass_density_g_per_L/molar_mass_NaCl # mol L^-1 # %% cNaCl_mM = np.round(cNaCl_M/sc.milli) # mM # %% cNaCl_mM # %% n_NaCl = np.round(cNaCl_mM*vol_mCube*sc.value('Avogadro constant')) # %% n_NaCl # %% c = [cNaCl_mM,cNaCl_mM] z = [1,-1] L=box_m[2] lamda_S = 2.0e-10 delta_u = 0.5 # %% pnp = PoissonNernstPlanckSystem(c,z,L, lambda_S=lambda_S, delta_u=delta_u, N=200, maxit=20, e=1e-6) # %% pnp.useSternLayerCellBC() # %% pnp.output = True xij = pnp.solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.set_xlabel('z [nm]') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_xlabel('z [nm]') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interfaces # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interfaces # %% (pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Cation concentration at interfaces # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interfaces # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # #### Equilibrium cation and anion amount # %% ( pnp.numberConservationConstraint(pnp.xij1,0,0), pnp.numberConservationConstraint(pnp.xij1,1,0) ) # %% [markdown] # #### Initial cation and anion amount # %% ( pnp.numberConservationConstraint(pnp.xi0,0,0), pnp.numberConservationConstraint(pnp.xi0,1,0) ) # %% [markdown] # #### Species conservation # %% (pnp.numberConservationConstraint(pnp.xij1,0, pnp.numberConservationConstraint(pnp.xi0,0,0)), pnp.numberConservationConstraint(pnp.xij1,1, pnp.numberConservationConstraint(pnp.xi0,1,0)) ) # %% [markdown] # ## Sampling # First, convert the physical concentration distributions into a callable "probability density": # %% pnp.concentration.shape # %% distributions = [interpolate.interp1d(pnp.grid,pnp.concentration[i,:]) for i in range(pnp.concentration.shape[0])] # %% [markdown] # Normalization is not necessary here. Now we can sample the distribution of our $Na^+$ ions in z-direction. # %% na_coordinate_sample = continuous2discrete( distribution=distributions[0], box=box_m, count=n_NaCl) histx, histy, histz = get_histogram(na_coordinate_sample, box=box_m, n_bins=51) plot_dist(histz, 'Distribution of Na+ ions in z-direction', reference_distribution=distributions[0]) # %% cl_coordinate_sample = continuous2discrete( distributions[1], box=box_m, count=n_NaCl) histx, histy, histz = get_histogram(cl_coordinate_sample, box=box_m, n_bins=51) plot_dist(histx, 'Distribution of Cl- ions in x-direction', reference_distribution=lambda x: np.ones(x.shape)*1/box_m[0]) plot_dist(histy, 'Distribution of Cl- ions in y-direction', reference_distribution=lambda x: np.ones(x.shape)*1/box_m[1]) plot_dist(histz, 'Distribution of Cl- ions in z-direction', reference_distribution=distributions[1]) # %% [markdown] # ## Write to file # To visualize our sampled coordinates, we utilize ASE to export it to some standard format, i.e. .xyz or LAMMPS data file. # ASE speaks Ångström per default, thus we convert SI units: # %% sample_size = int(n_NaCl) # %% sample_size # %% na_atoms = ase.Atoms( symbols='Na'*sample_size, charges=[1]*sample_size, positions=na_coordinate_sample/sc.angstrom, cell=box_Ang, pbc=[1,1,0]) cl_atoms = ase.Atoms( symbols='Cl'*sample_size, charges=[-1]*sample_size, positions=cl_coordinate_sample/sc.angstrom, cell=box_Ang, pbc=[1,1,0]) system = na_atoms + cl_atoms system ase.io.write('NaCl_c_4_M_u_0.5_V_box_5x5x10nm_lambda_S_2_Ang.xyz',system,format='xyz') # %% # LAMMPS data format, units 'real', atom style 'full' # before ASE 3.19.0b1, ASE had issues with exporting atom style 'full' in LAMMPS data file format, so do not expect this line to work for older ASE versions ase.io.write('NaCl_c_4_M_u_0.5_V_box_5x5x10nm_lambda_S_2_Ang.lammps',system,format='lammps-data',units="real",atom_style='full')
52,795
38.166172
491
py
matscipy
matscipy-master/examples/electrochemistry/to_html.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import argparse import os import nbformat as nbf from traitlets.config import Config from nbconvert.exporters import HTMLExporter from nbconvert.preprocessors import TagRemovePreprocessor def main(): """Convert .ipynb to .html.""" class ArgumentDefaultsAndRawDescriptionHelpFormatter( argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass parser = argparse.ArgumentParser( description=__doc__, formatter_class=ArgumentDefaultsAndRawDescriptionHelpFormatter) parser.add_argument('infile', metavar='IN', help='.py input file') parser.add_argument('outfile', metavar='OUT', nargs='?', help='.html output file', default=None) try: import argcomplete argcomplete.autocomplete(parser) # This supports bash autocompletion. To enable this, pip install # argcomplete, activate global completion, or add # eval "$(register-python-argcomplete lpad)" # into your .bash_profile or .bashrc except ImportError: pass args = parser.parse_args() if args.outfile is None: prefix, _ = os.path.splitext(args.infile) args.outfile = prefix + '.html' c = Config() # Configure tag removal c.TagRemovePreprocessor.remove_cell_tags = ('remove_cell',) c.TagRemovePreprocessor.remove_all_outputs_tags = ('remove_output',) c.TagRemovePreprocessor.remove_input_tags = ('remove_input',) c.TagRemovePreprocessor.enabled = True c.ExecutePreprocessor c.HTMLExporter.preprocessors = ['nbconvert.preprocessors.TagRemovePreprocessor'] (body, resources) = HTMLExporter(config=c).from_filename(args.infile) with open(args.outfile, 'w') as f: f.write(body) if __name__ == '__main__': main()
2,685
32.575
84
py
matscipy
matscipy-master/examples/electrochemistry/samples_pb_c2d.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # %% [markdown] # # Poisson-Boltzmann distribution & continuous2discrete # # *Johannes Hörmann, Lukas Elflein, 2019* # # from continuous electrochemical double layer theory to discrete coordinate sets # %% # for dynamic module reload during testing, code modifications take immediate effect # %load_ext autoreload # %autoreload 2 # %% # stretching notebook width across whole window from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) # %% # basics import logging import numpy as np import scipy.constants as sc import matplotlib.pyplot as plt # %% # sampling from scipy import interpolate from matscipy.electrochemistry import continuous2discrete from matscipy.electrochemistry import get_histogram from matscipy.electrochemistry.utility import plot_dist # %% # electrochemistry basics from matscipy.electrochemistry import debye, ionic_strength # %% # Poisson-Bolzmann distribution from matscipy.electrochemistry.poisson_boltzmann_distribution import gamma, potential, concentration, charge_density # %% # Poisson-Nernst-Planck solver from matscipy.electrochemistry import PoissonNernstPlanckSystem # %% # 3rd party file output import ase import ase.io # %% # PoissonNernstPlanckSystem makes extensive use of Python's logging module # configure logging: verbosity level and format as desired standard_loglevel = logging.INFO # standard_logformat = ''.join(("%(asctime)s", # "[ %(filename)s:%(lineno)s - %(funcName)s() ]: %(message)s")) standard_logformat = "[ %(filename)s:%(lineno)s - %(funcName)s() ]: %(message)s" # reset logger if previously loaded logging.shutdown() logging.basicConfig(level=standard_loglevel, format=standard_logformat, datefmt='%m-%d %H:%M') # in Jupyter notebooks, explicitly modifying the root logger necessary logger = logging.getLogger() logger.setLevel(standard_loglevel) # remove all handlers for h in logger.handlers: logger.removeHandler(h) # create and append custom handles ch = logging.StreamHandler() formatter = logging.Formatter(standard_logformat) ch.setFormatter(formatter) ch.setLevel(standard_loglevel) logger.addHandler(ch) # %% # Test 1 logging.info("Root logger") # %% # Test 2 logger.info("Root Logger") # %% # Debug Test logging.debug("Root logger") # %% [markdown] # # The Poisson-Boltzman Distribution # *Lukas Elflein, 2019* # # In order to understand lubrication better, we simulate thin layers of lubricant on a metallic surface, solvated in water. # Different structures of lubricant films are created by varying parameters like their concentration and the charge of the surface. # The lubricant is somewhat solvable in water, thus parts of the film will diffuse into the bulk water. # Lubricant molecules are charged, and their distribution is roughly exponential. # # As simplification, we first create a solution of ions (Na+, purple; Cl-, green) in water (not shown). # ![pic](https://i.ibb.co/Yh8DxVM/showpicture.png) # # Close to the positively charged metallic surface, the electric potential (red) will be highest, falling off exponentially when further away. # This potential attracts negatively charged Chlorine ions, and pushes positively charged Natrium ions away, resulting in a higher (lower) concentration of Clorine (Natrium) near the surface. # # # %% [markdown] # To calculate this, we first need to find out how ions are distributed in solution. # A good description of the concentrations of our ion species, $c_{\mathrm{Na}^+}$ and $c_{\mathrm{Cl}^-}$ or $c_i$ for $i \in \{\mathrm{Na}^+, \mathrm{Cl}^-\}$, is given by the solution to the Poisson-Boltzmann equation, here expressed with molar concentrations, Faraday constant and molar gas constant # # $ # \begin{align} # c_i(x) &= c_i^\infty e^{-F \phi(x)/R T}\\ # \phi(x) &= \frac{2 R T}{F} \log\left(\frac{1 + \gamma e^{-\kappa x}}{1- \gamma e^{-\kappa z}}\right) # \approx \frac{4 R T}{F} \gamma e^{-\kappa x} \\ # \gamma &= \tanh(\frac{F \phi_0}{4 R T})\\ # \kappa &= 1/\lambda_D\\ # \lambda_D &= \Big(\frac{\epsilon \epsilon_0 R T}{F^2 \sum_{i} c_i^\infty z_i^2} \Big)^\frac{1}{2} # \end{align} # $ # # or alternatively expressed with number concentrations, elementary charge and Boltzmann constant instead # # $ # \begin{align} # \rho_{i}(x) &= \rho_{i}^\infty e^{ -e \phi(z) \> / \> k_B T}\\ # \phi(x) &= \frac{2k_B T}{e} \> \log\left(\frac{1 + \gamma e^{-\kappa z}}{1- \gamma e^{-\kappa z}}\right) # \approx \frac{4k_B T}{e} \gamma e^{-\kappa x} \\ # \gamma &= \tanh\left(\frac{e\phi_0}{4k_B T}\right)\\ # \kappa &= 1/\lambda_D\\ # \lambda_D &= \left(\frac{\epsilon \epsilon_0 k_B T}{\sum_{i} \rho_i^\infty e^2 z_i^2} \right)^\frac{1}{2} # \end{align} # $ # # with # * $x$: distance from interface $[\mathrm{m}]$ # * $\phi_0$: potential at the surface $[\mathrm{V}]$ # * $\phi(z)$: potential in the solution $[\mathrm{V}]$ # * $k_B$: Boltzmann Constant $[\mathrm{J}\> \mathrm{K}^{-1}]$ # * $R$: molar gas constant $[\mathrm{J}\> \mathrm{mol}^{-1}\> \mathrm{K}^{-1}]$ # * $T$: temperature $[\mathrm{K}]$ # * $e$: elementary charge (or Euler's constant when exponentiated) $[\mathrm{C}]$ # * $F$: Faraday constant $[\mathrm{C}\> \mathrm{mol}^{-1}]$ # * $\gamma$: term from Gouy-Chapmann theory # * $\gamma \rightarrow 1$ for high potentials # * $\phi(z) \approx \phi_0 e^{-\kappa z}$ for low potentials $\phi_0 \rightarrow 0$ # * $\lambda_D$: Debye Length ($\approx 34.0\>\mathrm{nm}$ for NaCl, $10^{-4} \mathrm{M}$, $25^\circ \mathrm{C}$) # * $c{i}$: molar concentration of ion species $i$ $[\mathrm{mol}\> \mathrm{m}^{-3}]$ # * $c_{i}^\infty$: bulk molar concentration (at infinity, where the solution is homogeneous) $[\mathrm{mol}\> \mathrm{m}^{-3}]$ # * $\rho_{i}$: number concentration of ion species $i$ $[\mathrm{m}^{-3}]$ # * $\rho_{i}^\infty$: bulk number concentration $[\mathrm{m}^{-3}]$ # * $\epsilon$: relative permittivity of the solution $[1]$ # * $\epsilon_0$: vacuum permittivity $[\mathrm{F}\> \mathrm{m}^{-1}]$ # * $z_i$: number charge of species $i$ $[1]$ # # # These equations are implemented in `poisson_boltzmann_distribution.py` # %% # Notes on units # universal gas constant R = N_A * k_B, [R] = J mol^-1 K^-1 # Faraday constant F = N_a e, [F] = C mol^-1 print("Note on constants and units:") print("[F] = {}".format(sc.unit('Faraday constant'))) print("[R] = {}".format(sc.unit('molar gas constant'))) print("[e] = {}".format(sc.unit('elementary charge'))) print("[k_B] = {}".format(sc.unit('Boltzmann constant'))) print("F/R = {}".format(sc.value('Faraday constant')/sc.value('molar gas constant'))) print("e/k_B = {}".format(sc.value('elementary charge')/sc.value('Boltzmann constant'))) print("F/R = e/k_B !") # %% # Debye length of 0.1 mM NaCl aqueous solution c = [0.1,0.1] # mM z = [1,-1] deb = debye(c,z) print('Debye Length of 10^-4 M saltwater: {} nm (Target: 30.52 nm)'.format(round(deb/sc.nano, 2))) # %% C = np.logspace(-3, 3, 50) # mM, # NaCl molar mass 58.443 g/mol and solubility limit in water at about 360 g/L # means concentrations as high as a few M (mol/L), i.e. >> 1000 mM, are possible debyes = np.array([debye([c,c], [1,-1]) for c in C]) fig, (ax1,ax2) = plt.subplots( nrows=1, ncols=2, figsize=[12,4], constrained_layout=True) ax1.set_xlabel('concentration (mM)') # mM is mol / m^3 ax1.set_ylabel('Debye length at 25° [nm]') ax1.semilogx(C, debyes/sc.nano, marker='.') ax2.set_xlabel('concentration (mM)') # mM is mol / m^3 ax2.set_ylabel('Debye length at 25° [nm]') ax2.loglog(C, debyes/sc.nano, marker='.') plt.show() # %% [markdown] # The debye length depends on the concentration of ions in solution, at low concentrations it becomes large. We can reproduce literature debye lengths with our function, so everything looks good. # # ## Gamma Function # # Next we calculate the gamma function $\gamma = \tanh(\frac{e\Psi(0)}{4k_B T})$ # %% x = np.linspace(-0.5, 0.5, 40) gammas = gamma(x, 298.15) plt.xlabel('Potential $\phi$ (V)') plt.ylabel('$\gamma(\phi)$ at 298.15 K (1)') plt.plot(x, gammas, marker='o') plt.show() # %% [markdown] # ## Potential # # We plug these two functions into the expression for the potential # # $\phi(z) = \frac{2k_B T}{e} \log\Big(\frac{1 + \gamma e^{-\kappa z}}{1- \gamma e^{-\kappa z}}\Big) # \approx \frac{4k_B T}{e} \gamma e^{-\kappa z}$ # %% x = np.linspace(0, 2*10**-7, 10000) # 200 nm c = [0.1,0.1] z = [1,-1] psi = potential(x, c, z, u=0.05) plt.xlabel('x (nm)') plt.ylabel('Potential (V)') plt.plot(x/sc.nano, psi, marker='') plt.show() # %% [markdown] # The potential is smooth and looks roughly exponential. Everything good so far. # # ## Concentrations # # Now we obtain ion concentrations $c_i$ from the potential $\phi(x)$ via # # $c_{i}(x) = c_{i}^\infty e^{-F \phi(x) \> / \> R T}$ # %% x = np.linspace(0, 100*10**-9, 2000) c = [0.1,0.1] z = [1,-1] u = 0.05 phi = potential(x, c, z, u) C = concentration(x, c, z, u) rho = charge_density(x, c, z, u) # %% # potential and concentration distributions analytic solution # based on Poisson-Boltzmann equation for 0.1 mM NaCl aqueous solution # at interface def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) for sp in ax.spines.values(): sp.set_visible(False) deb = debye(c, z) fig, ax1 = plt.subplots(figsize=[18,5]) ax1.set_xlabel('x (nm)') ax1.plot(x/sc.nano, phi, marker='', color='red', label='Potential', linewidth=1, linestyle='--') ax1.set_ylabel('potential (V)') ax1.axvline(x=deb/sc.nano, label='Debye Length', color='orange') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='Bulk concentration of Na+ ions', color='grey', linewidth=1, linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='green', label='Na+ ions') ax2.plot(x/sc.nano, C[1], marker='', color='blue', label='Cl- ions') ax2.set_ylabel('concentration (mM)') ax3 = ax1.twinx() # Offset the right spine of par2. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, par2 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density', color='grey', linewidth=1, linestyle='--') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') #fig.legend(loc='center') ax2.legend(loc='upper right', bbox_to_anchor=(-0.1, 1.02),fontsize=15) ax1.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1, -0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # Potential and concentrations behave as expected. # # ## Sampling # First, convert the physical concentration distributions into a callable "probability density": # %% distributions = [interpolate.interp1d(x,c) for c in C] # %% [markdown] # Normalization is not necessary here. Now we can sample the distribution of our $Na^+$ ions in z-direction. # %% x = y = 50e-9 z = 100e-9 box = np.array([x, y, z]) sample_size = 1000 # %% from scipy import optimize # %% na_coordinate_sample = continuous2discrete( distribution=distributions[0], box=box, count=sample_size) histx, histy, histz = get_histogram(na_coordinate_sample, box=box, n_bins=51) plot_dist(histz, 'Distribution of Na+ ions in z-direction', reference_distribution=distributions[0]) # %% cl_coordinate_sample = continuous2discrete( distributions[1], box=box, count=sample_size) histx, histy, histz = get_histogram(cl_coordinate_sample, box=box, n_bins=51) plot_dist(histx, 'Distribution of Cl- ions in x-direction', reference_distribution=lambda x: np.ones(x.shape)*1/box[0]) plot_dist(histy, 'Distribution of Cl- ions in y-direction', reference_distribution=lambda x: np.ones(x.shape)*1/box[1]) plot_dist(histz, 'Distribution of Cl- ions in z-direction', reference_distribution=distributions[1]) # %% [markdown] # ## Write to file # To visualize our sampled coordinates, we utilize ASE to export it to some standard format, i.e. .xyz or LAMMPS data file. # ASE speaks Ångström per default, thus we convert SI units: # %% na_atoms = ase.Atoms( symbols='Na'*sample_size, charges=[1]*sample_size, positions=na_coordinate_sample/sc.angstrom, cell=box/sc.angstrom, pbc=[1,1,0]) cl_atoms = ase.Atoms( symbols='Cl'*sample_size, charges=[-1]*sample_size, positions=cl_coordinate_sample/sc.angstrom, cell=box/sc.angstrom, pbc=[1,1,0]) system = na_atoms + cl_atoms system ase.io.write('NaCl_0.1mM_0.05V_50x50x100nm_at_interface_poisson_boltzmann_distributed.xyz',system,format='xyz') # %% # LAMMPS data format, units 'real', atom style 'full' # before ASE 3.19.0b1, ASE had issues with exporting atom style 'full' in LAMMPS data file format, so do not expect this line to work for older ASE versions ase.io.write('NaCl_0.1mM_0.05V_50x50x100nm_at_interface_poisson_boltzmann_distributed.lammps',system,format='lammps-data',units="real",atom_style='full') # %% [markdown] # # General Poisson-Nernst-Planck System # %% [markdown] # For general systems, i.e. a nanogap between two electrodes with not necessarily binary electrolyte, no closed analytic solution exists. # Thus, we solve the full Poisson-Nernst-Planck system of equations. # %% [markdown] # A binary Poisson-Nernst-Planck system corresponds to the transport problem in semiconductor physics. # In this context, Debye length, charge carrier densities and potential are related as follows. # %% [markdown] # ## Excursus: Transport problem in PNP junction (German) # %% [markdown] # ### Debye length # %% [markdown] # Woher kommt die Debye-Länge # # $$ \lambda = \sqrt{ \frac{\varepsilon \varepsilon_0 k_B T}{q^2 n_i} }$$ # # als natürliche Längeneinheit des Transportptoblems? # # Hier ist $n_i$ eine Referenzladungsträgerdichte, in der Regel die intrinsische Ladungsträgerdichte. # In dem Beispiel mit $N^+NN^+$-dotiertem Halbleiter erzeugen wir durch unterschiedliches Doping an den Rändern die erhöhte Donatorendichte $N_D^+ = 10^{20} \mathrm{cm}^{-3}$ und im mitteleren Bereich "Standarddonatorendichte" $N_D = 10^{18} \mathrm{cm}^{-3}$. Nun können wir als Referenz $n_i = N_D$ wählen und die Donatorendichten als $N_D = 1 \cdot n_i$ und $N_D^+ = 100 \cdot n_i$ ausdrücken. Diese normierte Konzentration nennen wir einfach $\tilde{N}_D$: $N_D = \tilde{N}_D \cdot n_i$. # # Ein ionisierter Donator trägt die Ladung $q$, ein Ladungsträger (in unserem Fall ein Elektron) trägt die Elementarladung $-q$. Die Raumladungsdichte $\rho$ in der Poissongleichung # # $$ \nabla^2 \varphi = - \frac{\rho}{\varepsilon \varepsilon_0}$$ # # lässt sich also ganz einfach als $\rho = - (n - N_D) \cdot q = - (\tilde{n} - \tilde{N}_D) ~ n_i ~ q$ ausdrücken. # # Konventionell wird das Potential auf $u = \frac{\phi ~ q}{k_B ~ T}$ normiert. Die Poissongleichung nimmt damit die Form # # $$\frac{k_B ~ T}{q} \cdot \nabla^2 u = \frac{(\tilde{n} - \tilde{N}_D) ~ n_i ~ q }{\varepsilon \varepsilon_0}$$ # # oder auch # # $$ \frac{\varepsilon ~ \varepsilon_0 ~ k_B ~ T}{q^2 n_i} \cdot \nabla^2 u = \lambda^2 \cdot \nabla^2 u = \tilde{n} - \tilde{N}_D$$ # # # %% [markdown] # ### Dimensionless formulation # %% [markdown] # Poisson- und Drift-Diffusionsgleichung # # $$ # \lambda^2 \frac{\partial^2 u}{\partial x^2} = n - N_D # $$ # # $$ # \frac{\partial n}{\partial t} = - D_n \ \frac{\partial}{\partial x} \left( n \ \frac{\partial u}{\partial x} - \frac{\partial n}{\partial x} \right) + R # $$ # # Skaliert mit [l], [t]: # # $$ # \frac{\lambda^2}{[l]^2} \frac{\partial^2 u}{\partial \tilde{x}^2} = n - N # $$ # # und # # $$ # \frac{1}{[t]} \frac{\partial n}{\partial \tilde{t}} = - \frac{D_n}{[l]^2} \ \frac{\partial}{\partial x} \left( n \ \frac{\partial u}{\partial x} - \frac{\partial n}{\partial x} \right) + R # $$ # # oder # # $$ # \frac{\partial n}{\partial \tilde{t}} = - \tilde{D}_n \ \frac{\partial}{\partial x} \left( n \ \frac{\partial u}{\partial x} - \frac{\partial n}{\partial x} \right) + \tilde{R} # $$ # # mit # # $$ # \tilde{D}_n = D_n \frac{[t]}{[l]^2} \Leftrightarrow [t] = [l]^2 \ \frac{ \tilde{D}_n } { D_n } # $$ # # und # # $$ \tilde{R} = \frac{n - N_D}{\tilde{\tau}}$$ # # mit $\tilde{\tau} = \tau / [t]$. # # $\tilde{\lambda} = 1$ und $\tilde{D_n} = 1$ werden mit # $[l] = \lambda$ und $[t] = \frac{\lambda^2}{D_n}$ erreicht: # %% [markdown] # ### Discretization # %% [markdown] # Naive Diskretisierung (skaliert): # # $$ \frac{1}{\Delta x^2} ( u_{i+1}-2u_i+u_{i-1} ) = n_i - N_i $$ # # $$ \frac{1}{\Delta t} ( n_{i,j+1} - n_{i,j} ) = - \frac{1}{\Delta x^2} \cdot \left[ \frac{1}{4} (n_{i+1} - n_{i-1}) (u_{i+1} - u_{i-1}) + n_i ( u_{i+1} - 2 u_i + u_{i-1} ) - ( n_{i+1} - 2 n_i + n_{i-1} ) \right] + \frac{ n_i - N_i}{ \tilde{\tau} } $$ # # Stationär: # # $$ # u_{i+1}-2u_i+u_{i-1} - \Delta x^2 \cdot n_i + \Delta x^2 \cdot N_i = 0 # $$ # # und # # $$ # \frac{1}{4} (n_{i+1} - n_{i-1}) (u_{i+1} - u_{i-1}) + n_i ( u_{i+1} - 2 u_i + u_{i-1} ) - ( n_{i+1} - 2 n_i + n_{i-1} ) - \Delta x^2 \cdot \frac{ n_i - N_i}{ \tilde{\tau} } = 0 # $$ # %% [markdown] # ### Newton-Iteration für gekoppeltes nicht-lineares Gleichungssystem # %% [markdown] # Idee: Löse nicht-lineares Finite-Differenzen-Gleichungssystem über Newton-Verfahren # # $$ \vec{F}(\vec{x}_{k+1}) = F(\vec{x}_k + \Delta \vec{x}_k) \approx F(\vec{x}_k) + \mathbf{J_F}(\vec{x}_k) \cdot \Delta \vec{x}_k + \mathcal{O}(\Delta x^2)$$ # # mit Unbekannter $\vec{x_k} = \{u_1^k, \dots, u_N^k, n_1^k, \dots, n_N^k\}$ und damit # # $$ \Rightarrow \Delta \vec{x}_k = - \mathbf{J}_F^{-1} ~ F(\vec{x}_k)$$ # # wobei die Jacobi-Matrix $2N \times 2N$ Einträge # # $$ \mathbf{J}_{ij}(\vec{x}_k) = \frac{\partial F_i}{\partial x_j} (\vec{x}_k) $$ # # besitzt, die bei jedem Iterationsschritt für $\vec{x}_k$ ausgewertet werden. # Der tatsächliche Aufwand liegt in der Invertierung der Jacobi-Matrix, um in jeder Iteration $k$ den Korrekturschritt $\Delta \vec{x}_k$ zu finden.m # %% [markdown] # $F(x)$ wird wie unten definiert als: # # $$ # u_{i+1}-2u_i+u_{i-1} - \Delta x^2 \cdot n_i + \Delta x^2 \cdot N_i = 0 # $$ # # und # # $$ # \frac{1}{4} (n_{i+1} - n_{i-1}) (u_{i+1} - u_{i-1}) + n_i ( u_{i+1} - 2 u_i + u_{i-1} ) - ( n_{i+1} - 2 n_i + n_{i-1} ) - \Delta x^2 \cdot \frac{ n_i - N_i}{ \tilde{\tau} } = 0 # $$ # %% [markdown] # ### Controlled-Volume # %% [markdown] # Drücke nicht-linearen Teil der Transportgleichung (genauer, des Flusses) über Bernoulli-Funktionen # # $$ B(x) = \frac{x}{\exp(x)-1} $$ # # aus (siehe Vorlesungsskript). Damit wir in der Nähe von 0 nicht "in die Bredouille geraten", verwenden wir hier lieber die Taylorentwicklung. In der Literatur (Selbherr, S. Analysis and Simulation of Semiconductor Devices, Spriger 1984) wird eine noch aufwendigere stückweise Definition empfohlen, allerdings werden wir im Folgenden sehen, dass unser Ansatz für dieses stationäre Problem genügt. # # %% [markdown] # ## Implementation for Poisson-Nernst-Planck system # %% [markdown] # Poisson-Nernst-Planck system for $k = {1 \dots M}$ ion species in dimensionless formulation # # $$ \nabla^2 u + \rho(n_{1},\dots,n_{M}) = 0 $$ # # $$ \nabla^2 n_k + \nabla ( z_k n_k \nabla u ) = 0 \quad \text{for} \quad k = 1 \dots M $$ # # yields a naive finite difference discretization on $i = {1 \dots N}$ grid points for $k = {1 \dots M}$ ion species # # $$ \frac{1}{\Delta x^2} ( u_{i+1}-2u_i+u_{i-1} ) + \frac{1}{2} \sum_{k=1}^M z_k n_{i,k} = 0 $$ # # $$ - \frac{1}{\Delta x^2} \cdot \left[ \frac{1}{4} z_k (n_{i+1,k} - n_{i-1,k}) (u_{i+1} - u_{i-1}) + z_k n_{i,k} ( u_{i+1} - 2 u_i + u_{i-1} ) + ( n_{i+1,k} - 2 n_{i,k} + n_{i-1,k} ) \right] $$ # # or rearranged # # $$ u_{i+1}-2 u_i+u_{i-1} + \Delta x^2 \frac{1}{2} \sum_{k=1}^M z_k n_{i,k} = 0 $$ # # and # # $$ # \frac{1}{4} z_k (n_{i+1,k} - n_{i-1,k}) (u_{i+1,k} - u_{i-1,k}) + z_k n_{i,k} ( u_{i+1} - 2 u_i + u_{i-1} ) - ( n_{i+1,k} - 2 n_{i,k} + n_{i-1,k} ) = 0 # $$ # %% [markdown] # ### Controlled Volumes, 1D # %% [markdown] # Finite differences do not converge in our non-linear systems. Instead, we express non-linear part of the Nernts-Planck equations with Bernoulli function (Selberherr, S. Analysis and Simulation of Semiconductor Devices, Spriger 1984) # # $$ B(x) = \frac{x}{\exp(x)-1} $$ # %% def B(x): return np.where( np.abs(x) < 1e-9, 1 - x/2 + x**2/12 - x**4/720, # Taylor x / ( np.exp(x) - 1 ) ) # %% xB = np.arange(-10,10,0.1) # %% plt.plot( xB ,B( xB ), label="$B(x)$") plt.plot( xB, - B(-xB), label="$-B(-x)$") plt.plot( xB, B(xB)-B(-xB), label="$B(x)-B(-x)$") plt.legend() # %% [markdown] # Looking at (dimensionless) flux $j_k$ throgh segment $k$ in between grid points $i$ and $j$, # # $$ j_k = - \frac{dn}{dx} - z n \frac{du}{dx} $$ # # for an ion species with number charge $z$ and (dimensionless) concentration $n$, # we assume (dimensionless) potential $u$ to behave linearly within this segment. The linear expression # # $$ u = \frac{u_j - u_i}{L_k} \cdot \xi_k + u_i = a_k \xi_k + u_i $$ # # with the segment's length $L_k = \Delta x$ for uniform discretization, $\xi_k = x - x_i$ and proportionality factor $a_k = \frac{u_j - u_i}{L_k}$ leadsd to a flux # # $$ j_k = - \frac{dn}{d\xi} - z a_k n $$ # # solvable for $v$ via # # $$ \frac{dn}{d\xi} = - z a_k n - j_k $$ # # or # # $$ \frac{dn}{z a_k n + j_k} = - d\xi \text{.} $$ # # We intergate from grid point $i$ to $j$ # # $$ \int_{n_i}^{n_j} \frac{1}{z a_k n + j_k} dn = - L_k $$ # # and find # # $$ \frac{1}{(z a_k)} \left[ \ln(j_k + z a_k n) \right]_{n_i}^{n^j} = - L_k $$ # # or # # $$ \ln(j_k + z a_k n_j) - \ln(j_k + z a_k n_i) = - z a_k L_k $$ # # which we solve for $j_k$ by rearranging # # $$ \frac{j_k + z a_k n_j}{j_k + z a_k n_i} = e^{- z a_k L_k} $$ # # $$ j_k + z a_k n_j = (j_k + z a_k n_i) e^{- z a_k L_k} $$ # # $$ j_k ( 1 - e^{- z a_k L_k} ) = - z a_k n_j + z a_k n_i e^{- z a_k L_k} $$ # # $$j_k = \frac{z a_k n_j}{e^{- z a_k L_k} - 1} + \frac{ z a_k n_i e^{- z a_k L_k}}{ 1 - e^{- z a_k L_k}}$$ # # $$j_k = \frac{1}{L_k} \cdot \left[ \frac{z a_k L_k n_j}{e^{- z a_k L_k} - 1} + \frac{ z a_k L_k n_i }{ e^{z a_k L_k} - 1} \right] $$ # # or with $B(x) = \frac{x}{e^x-1}$ expressed as # # $$j_k = \frac{1}{L_k} \cdot \left[ - n_j B( - z a_k L_k ) + n_i B( z a_k L_k) \right] $$ # # and resubstituting $a_k = \frac{u_j - u_i}{L_k}$ as # # $$j_k = - \frac{1}{L_k} \cdot \left[ n_j B( z [u_i - u_j] ) - n_i B( z [u_j - u_i] ) \right] \ \text{.}$$ # # When employing our 1D uniform grid with $j_k = j_{k-1}$ for all $k = 1 \dots N$, # # $$ j_k \Delta x = n_{i+1} B( z [u_i - u_{i+1}] ) - n_i B( z [u_{i+1} - u_i] ) $$ # # and # # $$ j_{k-1} \Delta x = n_i B( z [u_{i-1} - u_i] ) - n_{i-1} B( z [u_i - u_{i-1}] ) $$ # # require # # $$ n_{i+1} B( z [u_i - u_{i+1}] ) - n_i \left( B( z [u_{i+1} - u_i] ) + B( z [u_{i-1} - u_i] ) \right) + n_{i-1} B( z [u_i - u_{i-1}] ) = 0 $$ # %% [markdown] # ## Test case 1: PNP interface system, 0.1 mM NaCl, positive potential u = 0.05 V # %% # Test case parameters c=[0.1, 0.1] z=[ 1, -1] L=1e-07 delta_u=0.05 # %% # define desired system pnp = PoissonNernstPlanckSystem(c, z, L, delta_u=delta_u) # constructor takes keyword arguments # c=array([0.1, 0.1]), z=array([ 1, -1]), L=1e-07, T=298.15, delta_u=0.05, relative_permittivity=79, vacuum_permittivity=8.854187817620389e-12, R=8.3144598, F=96485.33289 # with default values set for 0.1 mM NaCl aqueous solution across 100 nm and 0.05 V potential drop # %% pnp.useStandardInterfaceBC() # %% pnp.output = True # let's Newton solver display convergence plots uij, nij, lamj = pnp.solve() # %% [markdown] # ### Validation: Analytical half-space solution & Numerical finite-size PNP system # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax1.plot(x/sc.nano, phi, marker='', color='tomato', label='potential, PB', linewidth=1, linestyle='--') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='Charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interface and at open right hand side # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interface and at open right hand side # %% (pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Cation concentration at interface and at open right hand side # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interface and at open right hand side # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # ## Test case 2: PNP interface system, 0.1 mM NaCl, negative potential u = -0.05 V, analytical solution as initial values # %% # Test case parameters c=[0.1, 0.1] z=[ 1, -1] L=1e-07 delta_u=-0.05 # %% pnp = PoissonNernstPlanckSystem(c, z, L, delta_u=delta_u) # %% pnp.useStandardInterfaceBC() # %% pnp.init() # %% # initial config x = np.linspace(0, pnp.L, pnp.Ni) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) # %% pnp.ni0 = C / pnp.c_unit # manually remove dimensions from analyatical solution # %% ui0 = pnp.initial_values() # %% plt.plot(ui0) # solution to linear Poisson equation under assumption of fixed charge density distribution # %% pnp.output = True # let's Newton solver display convergence plots uij, nij, lamj = pnp.solve() # no faster convergence than above, compare convergence plots for test case 1 # %% [markdown] # ### Validation: Analytical half-space solution & Numerical finite-size PNP system # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax1.plot(x/sc.nano, phi, marker='', color='tomato', label='potential, PB', linewidth=1, linestyle='--') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='Charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interface and at open right hand side # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interface and at open right hand side # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,1) ) # %% [markdown] # #### Cation concentration at interface and at open right hand side # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interface and at open right hand side # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # ## Test case 3: PNP interface system, 0.1 mM NaCl, positive potential u = 0.05 V, 200 nm domain # %% # Test case parameters c=[0.1, 0.1] z=[ 1, -1] L=2e-07 delta_u=0.05 # %% pnp = PoissonNernstPlanckSystem(c, z, L, delta_u=delta_u) # %% pnp.useStandardInterfaceBC() # %% pnp.init() # %% pnp.output = True uij, nij, lamj = pnp.solve() # %% [markdown] # ### Validation: Analytical half-space solution & Numerical finite-size PNP system # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax1.plot(x/sc.nano, phi, marker='', color='tomato', label='potential, PB', linewidth=1, linestyle='--') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='Charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # Analytic PB and approximate PNP solution indistinguishable. # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interface and at open right hand side # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interface and at open right hand side # %% (pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Cation concentration at interface and at open right hand side # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interface and at open right hand side # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # ## Test case 4: 1D electrochemical cell, 0.1 mM NaCl, positive potential u = 0.05 V, 100 nm domain # %% # Test case parameters c=[0.1, 0.1] z=[ 1, -1] L=1e-07 delta_u=0.05 # %% pnp = PoissonNernstPlanckSystem(c, z, L, delta_u=delta_u) # %% pnp.useStandardCellBC() # %% pnp.init() # %% pnp.output = True xij = pnp.solve() # %% [markdown] # ### Validation: Analytical half-space solution & Numerical finite-size PNP system # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) phi = potential(x, c, z, delta_u) C = concentration(x, c, z, delta_u) rho = charge_density(x, c, z, delta_u) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax1.plot(x/sc.nano, phi, marker='', color='tomato', label='potential, PB', linewidth=1, linestyle='--') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax2.plot(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(x/sc.nano, rho, label='Charge density, PB', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='Charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='bulk concentration', color='grey', linestyle=':') ax4.semilogy(x/sc.nano, C[0], marker='', color='bisque', label='Na+, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(x/sc.nano, C[1], marker='', color='lightskyblue', label='Cl-, PB',linestyle='--') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.set_xlabel('z [nm]') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_xlabel('z [nm]') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interfaces # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interfaces # %% (pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Cation concentration at interfaces # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interfaces # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # #### Equilibrium cation and anion amount # %% ( pnp.numberConservationConstraint(pnp.xij1,0,0), pnp.numberConservationConstraint(pnp.xij1,1,0) ) # %% [markdown] # #### Initial cation and anion amount # %% ( pnp.numberConservationConstraint(pnp.xi0,0,0), pnp.numberConservationConstraint(pnp.xi0,1,0) ) # %% [markdown] # #### Species conservation # %% (pnp.numberConservationConstraint(pnp.xij1,0, pnp.numberConservationConstraint(pnp.xi0,0,0)), pnp.numberConservationConstraint(pnp.xij1,1, pnp.numberConservationConstraint(pnp.xi0,1,0)) ) # %% [markdown] # ## Test case 5: 1D electrochemical cell, 0.1 mM NaCl, positive potential u = 0.05 V, 100 nm domain, 0.5 nm compact layer # %% [markdown] # At high potentials or bulk concentrations, pure PNP systems yield unphysically high concentrations and steep gradients close to the boundary, as an ion's finite size is not accounted for. # In addition, high gradients can lead to convergence issues. This problem can be alleviated by assuming a Stern layer (compact layer) at the interface. # This compact layer is parametrized by its thickness $\lambda_S$ and can be treated explicitly by prescribing a linear potential regime across the compact layer region, or by # the implicit parametrization of a compact layer with uniform charge density as Robin boundary conditions on the potential. # %% c = [1000,1000] # high concentrations close to NaCl's solubility limit in water delta_u = 0.05 L = 30e-10 # tiny gap of 3 nm lambda_S = 5e-10 # 0.5 nm Stern layer # %% pnp_no_compact_layer = PoissonNernstPlanckSystem(c,z,L,delta_u=delta_u, e=1e-12) # %% pnp_with_explicit_compact_layer = PoissonNernstPlanckSystem(c,z,L, delta_u=delta_u,lambda_S=lambda_S, e=1e-12) # %% pnp_with_implicit_compact_layer = PoissonNernstPlanckSystem(c,z,L, delta_u=delta_u,lambda_S=lambda_S, e=1e-12) # %% pnp_no_compact_layer.useStandardCellBC() # %% pnp_with_explicit_compact_layer.useSternLayerCellBC(implicit=False) # %% pnp_with_implicit_compact_layer.useSternLayerCellBC(implicit=True) # %% pnp_no_compact_layer.init() # %% pnp_with_explicit_compact_layer.init() # %% pnp_with_implicit_compact_layer.init() # %% pnp_no_compact_layer.output = True xij_no_compact_layer = pnp_no_compact_layer.solve() # %% pnp_with_explicit_compact_layer.output = True xij_with_explicit_compact_layer = pnp_with_explicit_compact_layer.solve() # %% pnp_with_implicit_compact_layer.output = True xij_with_implicit_compact_layer = pnp_with_implicit_compact_layer.solve() # %% x = np.linspace(0,L,100) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[18,10]) # 1 - potentials ax1.axvline(x=deb/sc.nano, label='Debye Length', color='grey', linestyle=':') ax1.plot(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.potential, marker='', color='tab:red', label='potential, without compact layer', linewidth=1, linestyle='-') ax1.plot(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.potential, marker='', color='tab:red', label='potential, with explicit compact layer', linewidth=1, linestyle='--') ax1.plot(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.potential, marker='', color='tab:red', label='potential, with Robin BC', linewidth=2, linestyle=':') # 2 - conencentratiosn ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax2.plot(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, without compact layer', linewidth=2, linestyle='-') ax2.plot(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, without compact layer', linewidth=2, linestyle='-') ax2.plot(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, with explicit compact layer', linewidth=2, linestyle='--') ax2.plot(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, with explicit compact layer', linewidth=2, linestyle='--') ax2.plot(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, with Robin BC', linewidth=2, linestyle=':') ax2.plot(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, with Robin BC', linewidth=2, linestyle=':') # 3 - charge densities ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.charge_density, label='charge density, without compact layer', color='grey', linewidth=1, linestyle='-') ax3.plot(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.charge_density, label='charge density, with explicit compact layer', color='grey', linewidth=1, linestyle='--') ax3.plot(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.charge_density, label='charge density, with Robin BC', color='grey', linewidth=1, linestyle=':') # 4 - concentrations, semi log ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax4.semilogy(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, without compact layer', linewidth=2, linestyle='-') ax4.semilogy(pnp_no_compact_layer.grid/sc.nano, pnp_no_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, without compact layer', linewidth=2, linestyle='-') ax4.semilogy(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, with explicit compact layer', linewidth=2, linestyle='--') ax4.semilogy(pnp_with_explicit_compact_layer.grid/sc.nano, pnp_with_explicit_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, with explicit compact layer', linewidth=2, linestyle='--') ax4.semilogy(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.concentration[0], marker='', color='tab:orange', label='Na+, with Robin BC', linewidth=2, linestyle=':') ax4.semilogy(pnp_with_implicit_compact_layer.grid/sc.nano, pnp_with_implicit_compact_layer.concentration[1], marker='', color='tab:blue', label='Cl-, with Robin BC', linewidth=2, linestyle=':') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') #ax3.yaxis.set_major_formatter(formatter) ax3.ticklabel_format(axis='y', style='sci', scilimits=(-2,10), useOffset=False, useMathText=False) ax4.set_xlabel('z [nm]') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=12) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=12) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=12) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp_no_compact_layer.potential[0],pnp_no_compact_layer.potential[-1]) # %% (pnp_with_explicit_compact_layer.potential[0],pnp_with_explicit_compact_layer.potential[-1]) # %% (pnp_with_implicit_compact_layer.potential[0],pnp_with_implicit_compact_layer.potential[-1]) # %% [markdown] # #### Residual cation flux at interfaces # %% ( pnp_no_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_no_compact_layer.xij1,0), pnp_no_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_no_compact_layer.xij1,0) ) # %% ( pnp_with_explicit_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_with_explicit_compact_layer.xij1,0), pnp_with_explicit_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_with_explicit_compact_layer.xij1,0) ) # %% ( pnp_with_implicit_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_with_implicit_compact_layer.xij1,0), pnp_with_implicit_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_with_implicit_compact_layer.xij1,0) ) # %% [markdown] # #### Residual cation flux at interfaces # %% ( pnp_no_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_no_compact_layer.xij1,1), pnp_no_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_no_compact_layer.xij1,1) ) # %% ( pnp_with_explicit_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_with_explicit_compact_layer.xij1,1), pnp_with_explicit_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_with_explicit_compact_layer.xij1,1) ) # %% ( pnp_with_implicit_compact_layer.leftControlledVolumeSchemeFluxBC(pnp_with_implicit_compact_layer.xij1,1), pnp_with_implicit_compact_layer.rightControlledVolumeSchemeFluxBC(pnp_with_implicit_compact_layer.xij1,1) ) # %% [markdown] # #### Cation concentration at interfaces # %% (pnp_no_compact_layer.concentration[0,0],pnp_no_compact_layer.concentration[0,-1]) # %% (pnp_with_explicit_compact_layer.concentration[0,0],pnp_with_explicit_compact_layer.concentration[0,-1]) # %% (pnp_with_implicit_compact_layer.concentration[0,0],pnp_with_implicit_compact_layer.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interfaces # %% (pnp_no_compact_layer.concentration[1,0],pnp_no_compact_layer.concentration[1,-1]) # %% (pnp_with_explicit_compact_layer.concentration[1,0],pnp_with_explicit_compact_layer.concentration[1,-1]) # %% (pnp_with_implicit_compact_layer.concentration[1,0],pnp_with_implicit_compact_layer.concentration[1,-1]) # %% [markdown] # #### Equilibrium cation and anion amount # %% ( pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xij1,0,0), pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xij1,1,0) ) # %% ( pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xij1,0,0), pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xij1,1,0) ) # %% ( pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xij1,0,0), pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xij1,1,0) ) # %% [markdown] # #### Initial cation and anion amount # %% ( pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xi0,0,0), pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xi0,1,0) ) # %% ( pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xi0,0,0), pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xi0,1,0) ) # %% ( pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xi0,0,0), pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xi0,1,0) ) # %% [markdown] # #### Species conservation # %% (pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xij1,0, pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xi0,0,0)), pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xij1,1, pnp_no_compact_layer.numberConservationConstraint(pnp_no_compact_layer.xi0,1,0)) ) # %% (pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xij1,0, pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xi0,0,0)), pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xij1,1, pnp_with_explicit_compact_layer.numberConservationConstraint(pnp_with_explicit_compact_layer.xi0,1,0)) ) # %% (pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xij1,0, pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xi0,0,0)), pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xij1,1, pnp_with_implicit_compact_layer.numberConservationConstraint(pnp_with_implicit_compact_layer.xi0,1,0)) ) # %% [markdown] # ## Sample application of 1D electrochemical cell model: # %% [markdown] # We want to fill a gap of 3 nm between gold electrodes with 0.2 wt % NaCl aqueous solution, apply a small potential difference and generate an initial configuration for LAMMPS within a cubic box: # %% box_Ang=np.array([50.,50.,50.]) # Angstrom # %% box_m = box_Ang*sc.angstrom # %% box_m # %% vol_AngCube = box_Ang.prod() # Angstrom^3 # %% vol_mCube = vol_AngCube*sc.angstrom**3 # %% [markdown] # With a concentration of 0.2 wt %, we are close to NaCl's solubility limit in water. # We estimate molar concentrations and atom numbers in our box: # %% # enter number between 0 ... 0.2 weight_concentration_NaCl = 0.2 # wt % # calculate saline mass density g/cm³ saline_mass_density_kg_per_L = 1 + weight_concentration_NaCl * 0.15 / 0.20 # g / cm^3, kg / L # see https://www.engineeringtoolbox.com/density-aqueous-solution-inorganic-sodium-salt-concentration-d_1957.html # %% saline_mass_density_g_per_L = saline_mass_density_kg_per_L*sc.kilo # %% molar_mass_H2O = 18.015 # g / mol molar_mass_NaCl = 58.44 # g / mol # %% cNaCl_M = weight_concentration_NaCl*saline_mass_density_g_per_L/molar_mass_NaCl # mol L^-1 # %% cNaCl_mM = np.round(cNaCl_M/sc.milli) # mM # %% cNaCl_mM # %% n_NaCl = np.round(cNaCl_mM*vol_mCube*sc.value('Avogadro constant')) # %% n_NaCl # %% c = [cNaCl_mM,cNaCl_mM] z = [1,-1] L=box_m[2] lamda_S = 2.0e-10 delta_u = 0.5 # %% pnp = PoissonNernstPlanckSystem(c,z,L, lambda_S=lambda_S, delta_u=delta_u, N=200, maxit=20, e=1e-6) # %% pnp.useSternLayerCellBC() # %% pnp.init() # %% pnp.output = True xij = pnp.solve() # %% # analytic Poisson-Boltzmann distribution and numerical solution to full Poisson-Nernst-Planck system x = np.linspace(0,L,100) deb = debye(c, z) fig, (ax1,ax4) = plt.subplots(nrows=2,ncols=1,figsize=[16,10]) ax1.set_xlabel('z [nm]') ax1.plot(pnp.grid/sc.nano, pnp.potential, marker='', color='tab:red', label='potential, PNP', linewidth=1, linestyle='-') ax2 = ax1.twinx() ax2.plot(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax2.plot(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax2.plot(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.axvline(x=deb, label='Debye Length', color='grey', linestyle=':') ax3 = ax1.twinx() # Offset the right spine of ax3. The ticks and label have already been # placed on the right by twinx above. ax3.spines["right"].set_position(("axes", 1.1)) # Having been created by twinx, ax3 has its frame off, so the line of its # detached spine is invisible. First, activate the frame but make the patch # and spines invisible. make_patch_spines_invisible(ax3) # Second, show the right spine. ax3.spines["right"].set_visible(True) ax3.plot(pnp.grid/sc.nano, pnp.charge_density, label='charge density, PNP', color='grey', linewidth=1, linestyle='-') ax4.semilogy(x/sc.nano, np.ones(x.shape)*c[0], label='average concentration', color='grey', linestyle=':') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[0], marker='', color='tab:orange', label='Na+, PNP', linewidth=2, linestyle='-') ax4.semilogy(pnp.grid/sc.nano, pnp.concentration[1], marker='', color='tab:blue', label='Cl-, PNP', linewidth=2, linestyle='-') ax1.set_xlabel('z [nm]') ax1.set_ylabel('potential (V)') ax2.set_ylabel('concentration (mM)') ax3.set_ylabel(r'charge density $\rho \> (\mathrm{C}\> \mathrm{m}^{-3})$') ax4.set_xlabel('z [nm]') ax4.set_ylabel('concentration (mM)') #fig.legend(loc='center') ax1.legend(loc='upper right', bbox_to_anchor=(-0.1,1.02), fontsize=15) ax2.legend(loc='center right', bbox_to_anchor=(-0.1,0.5), fontsize=15) ax3.legend(loc='lower right', bbox_to_anchor=(-0.1,-0.02), fontsize=15) fig.tight_layout() plt.show() # %% [markdown] # #### Potential at left and right hand side of domain # %% (pnp.potential[0],pnp.potential[-1]) # %% [markdown] # #### Residual cation flux at interfaces # %% ( pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,0), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Residual anion flux at interfaces # %% (pnp.leftControlledVolumeSchemeFluxBC(pnp.xij1,1), pnp.rightControlledVolumeSchemeFluxBC(pnp.xij1,0) ) # %% [markdown] # #### Cation concentration at interfaces # %% (pnp.concentration[0,0],pnp.concentration[0,-1]) # %% [markdown] # #### Anion concentration at interfaces # %% (pnp.concentration[1,0],pnp.concentration[1,-1]) # %% [markdown] # #### Equilibrium cation and anion amount # %% ( pnp.numberConservationConstraint(pnp.xij1,0,0), pnp.numberConservationConstraint(pnp.xij1,1,0) ) # %% [markdown] # #### Initial cation and anion amount # %% ( pnp.numberConservationConstraint(pnp.xi0,0,0), pnp.numberConservationConstraint(pnp.xi0,1,0) ) # %% [markdown] # #### Species conservation # %% (pnp.numberConservationConstraint(pnp.xij1,0, pnp.numberConservationConstraint(pnp.xi0,0,0)), pnp.numberConservationConstraint(pnp.xij1,1, pnp.numberConservationConstraint(pnp.xi0,1,0)) ) # %% [markdown] # ## Sampling # First, convert the physical concentration distributions into a callable "probability density": # %% pnp.concentration.shape # %% distributions = [interpolate.interp1d(pnp.grid,pnp.concentration[i,:]) for i in range(pnp.concentration.shape[0])] # %% [markdown] # Normalization is not necessary here. Now we can sample the distribution of our $Na^+$ ions in z-direction. # %% na_coordinate_sample = continuous2discrete( distribution=distributions[0], box=box_m, count=n_NaCl) histx, histy, histz = get_histogram(na_coordinate_sample, box=box_m, n_bins=51) plot_dist(histz, 'Distribution of Na+ ions in z-direction', reference_distribution=distributions[0]) # %% cl_coordinate_sample = continuous2discrete( distributions[1], box=box_m, count=n_NaCl) histx, histy, histz = get_histogram(cl_coordinate_sample, box=box_m, n_bins=51) plot_dist(histx, 'Distribution of Cl- ions in x-direction', reference_distribution=lambda x: np.ones(x.shape)*1/box[0]) plot_dist(histy, 'Distribution of Cl- ions in y-direction', reference_distribution=lambda x: np.ones(x.shape)*1/box[1]) plot_dist(histz, 'Distribution of Cl- ions in z-direction', reference_distribution=distributions[1]) # %% [markdown] # ## Write to file # To visualize our sampled coordinates, we utilize ASE to export it to some standard format, i.e. .xyz or LAMMPS data file. # ASE speaks Ångström per default, thus we convert SI units: # %% sample_size = int(n_NaCl) # %% sample_size # %% na_atoms = ase.Atoms( symbols='Na'*sample_size, charges=[1]*sample_size, positions=na_coordinate_sample/sc.angstrom, cell=box_Ang, pbc=[1,1,0]) cl_atoms = ase.Atoms( symbols='Cl'*sample_size, charges=[-1]*sample_size, positions=cl_coordinate_sample/sc.angstrom, cell=box_Ang, pbc=[1,1,0]) system = na_atoms + cl_atoms system ase.io.write('NaCl_c_4_M_u_0.5_V_box_5x5x10nm_lambda_S_2_Ang.xyz',system,format='xyz') # %% # LAMMPS data format, units 'real', atom style 'full' # before ASE 3.19.0b1, ASE had issues with exporting atom style 'full' in LAMMPS data file format, so do not expect this line to work for older ASE versions ase.io.write('NaCl_c_4_M_u_0.5_V_box_5x5x10nm_lambda_S_2_Ang.lammps',system,format='lammps-data',units="real",atom_style='full')
63,781
37.422892
491
py
matscipy
matscipy-master/examples/electrochemistry/pnp_batch/interface_1d/concentration_sweep/pnp_plot.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os.path, re, sys import numpy as np from glob import glob from cycler import cycler from itertools import cycle from itertools import groupby import matplotlib.pyplot as plt # Ensure variable is defined try: datadir except NameError: try: datadir = sys.argv[1] except: datadir = 'data' try: figfile except NameError: try: figfile = sys.argv[2] except: figfile = 'fig.png' try: param except NameError: try: param = sys.argv[3] except: param = 'c' try: param_unit except NameError: try: param_label = sys.argv[4] except: param_label = 'c (\mathrm{mM})' try: glob_pattern except NameError: glob_pattern = os.path.join(datadir, 'NaCl*.txt') def right_align_legend(leg): hp = leg._legend_box.get_children()[1] for vp in hp.get_children(): for row in vp.get_children(): row.set_width(100) # need to adapt this manually row.mode= "expand" row.align="right" # sort file names as normal humans expect # https://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python def alpha_num_order(x): """Sort the given iterable in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text return [ convert(c) for c in re.split('([0-9]+)', x) ] dat_files = sorted(glob(glob_pattern),key=alpha_num_order) N = len(dat_files) # number of data sets M = 2 # number of species # matplotlib settings SMALL_SIZE = 8 MEDIUM_SIZE = 12 BIGGER_SIZE = 16 # plt.rc('axes', prop_cycle=default_cycler) plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure titlex plt.rcParams["figure.figsize"] = (16,10) # the standard figure size plt.rcParams["lines.linewidth"] = 3 plt.rcParams["lines.markersize"] = 14 plt.rcParams["lines.markeredgewidth"]=1 # line styles # https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html # linestyle_str = [ # ('solid', 'solid'), # Same as (0, ()) or '-' # ('dotted', 'dotted'), # Same as (0, (1, 1)) or '.' # ('dashed', 'dashed'), # Same as '--' # ('dashdot', 'dashdot')] # Same as '-.' linestyle_tuple = [ ('loosely dotted', (0, (1, 10))), ('dotted', (0, (1, 1))), ('densely dotted', (0, (1, 1))), ('loosely dashed', (0, (5, 10))), ('dashed', (0, (5, 5))), ('densely dashed', (0, (5, 1))), ('loosely dashdotted', (0, (3, 10, 1, 10))), ('dashdotted', (0, (3, 5, 1, 5))), ('densely dashdotted', (0, (3, 1, 1, 1))), ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))), ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))), ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))] # color maps for potential and concentration plots cmap_u = plt.get_cmap('Reds') cmap_c = [plt.get_cmap('Oranges'), plt.get_cmap('Blues')] # general line style cycler line_cycler = cycler( linestyle = [ s for _,s in linestyle_tuple ] ) # potential anc concentration cyclers u_cycler = cycler( color = cmap_u( np.linspace(0.4,0.8,N) ) ) u_cycler = len(line_cycler)*u_cycler + len(u_cycler)*line_cycler c_cyclers = [ cycler( color = cmap( np.linspace(0.4,0.8,N) ) ) for cmap in cmap_c ] c_cyclers = [ len(line_cycler)*c_cycler + len(c_cycler)*line_cycler for c_cycler in c_cyclers ] # https://matplotlib.org/3.1.1/tutorials/intermediate/constrainedlayout_guide.html fig, (ax1,ax2,ax3) = plt.subplots( nrows=1, ncols=3, figsize=[24,7], constrained_layout=True) ax1.set_xlabel('z (nm)') ax1.set_ylabel('potential (V)') ax2.set_xlabel('z (nm)') ax2.set_ylabel('concentration (mM)') ax3.set_xlabel('z (nm)') ax3.set_ylabel('concentration (mM)') # ax1.axvline(x=pnp.lambda_D()*1e9, label='Debye Length', color='grey', linestyle=':') species_label = [ '$[\mathrm{Na}^+], ' + param_label + '$', '$[\mathrm{Cl}^-], ' + param_label + '$'] c_regex = re.compile(r'{}_(-?\d+(,\d+)*(\.\d+(e\d+)?)?)'.format(param)) c_graph_handles = [ [] for _ in range(M) ] for f, u_style, c_styles in zip(dat_files,u_cycler,zip(*c_cyclers)): print("Processing {:s}".format(f)) # extract nominal concentration from file name nominal_c = float( c_regex.search(f).group(1) ) dat = np.loadtxt(f,unpack=True) x = dat[0,:] u = dat[1,:] c = dat[2:,:] c_label = '{:> 4.1f}'.format(nominal_c) # potential ax1.plot(x*1e9, u, marker=None, label=c_label, linewidth=1, **u_style) for i in range(c.shape[0]): # concentration ax2.plot(x*1e9, c[i], marker='', label=c_label, linewidth=2, **c_styles[i]) # log-log concentration c_graph_handles[i].extend( ax3.loglog(x*1e9, c[i], marker='', label=c_label, linewidth=2, **c_styles[i]) ) # legend placement # https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot u_legend = ax1.legend(loc='center right', title='potential, ${}$'.format(param_label), bbox_to_anchor=(-0.2,0.5) ) first_c_legend = ax3.legend(handles=c_graph_handles[0], title=species_label[0], loc='upper left', bbox_to_anchor=(1.00, 1.02) ) second_c_legend = ax3.legend(handles=c_graph_handles[1], title=species_label[1], loc='lower left', bbox_to_anchor=(1.00,-0.02) ) ax3.add_artist(first_c_legend) # add automatically removed first legend again c_legends = [ first_c_legend, second_c_legend ] legends = [ u_legend, *c_legends ] for l in legends: right_align_legend(l) # https://matplotlib.org/3.1.1/tutorials/intermediate/constrainedlayout_guide.html for l in legends: l.set_in_layout(False) # trigger a draw so that constrained_layout is executed once # before we turn it off when printing.... fig.canvas.draw() # we want the legend included in the bbox_inches='tight' calcs. for l in legends: l.set_in_layout(True) # we don't want the layout to change at this point. fig.set_constrained_layout(False) # fig.tight_layout(pad=3.0, w_pad=2.0, h_pad=1.0) # plt.show() fig.savefig(figfile, bbox_inches='tight', dpi=100)
7,312
33.333333
128
py
matscipy
matscipy-master/examples/electrochemistry/pnp_batch/cell_1d/potential_sweep/pnp_plot.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os.path, re, sys import numpy as np from glob import glob from cycler import cycler from itertools import cycle from itertools import groupby import matplotlib.pyplot as plt # Ensure variable is defined try: datadir except NameError: try: datadir = sys.argv[1] except: datadir = 'data' try: figfile except NameError: try: figfile = sys.argv[2] except: figfile = 'fig.png' try: param except NameError: try: param = sys.argv[3] except: param = 'c' try: param_unit except NameError: try: param_label = sys.argv[4] except: param_label = 'c (\mathrm{mM})' try: glob_pattern except NameError: glob_pattern = os.path.join(datadir, 'NaCl*.txt') def right_align_legend(leg): hp = leg._legend_box.get_children()[1] for vp in hp.get_children(): for row in vp.get_children(): row.set_width(100) # need to adapt this manually row.mode= "expand" row.align="right" # sort file names as normal humans expect # https://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python scientific_number_regex = '([-+]?[\d]+\.?[\d]*(?:[Ee][-+]?[\d]+)?)' def alpha_num_order(x): """Sort the given iterable in the way that humans expect.""" def convert(text): try: ret = float(text) # if text.isdigit() else text except: ret = text return ret return [ convert(c) for c in re.split(scientific_number_regex, x) ] dat_files = sorted(glob(glob_pattern),key=alpha_num_order) N = len(dat_files) # number of data sets M = 2 # number of species # matplotlib settings SMALL_SIZE = 8 MEDIUM_SIZE = 12 BIGGER_SIZE = 16 # plt.rc('axes', prop_cycle=default_cycler) plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure titlex plt.rcParams["figure.figsize"] = (16,10) # the standard figure size plt.rcParams["lines.linewidth"] = 3 plt.rcParams["lines.markersize"] = 14 plt.rcParams["lines.markeredgewidth"]=1 # line styles # https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html # linestyle_str = [ # ('solid', 'solid'), # Same as (0, ()) or '-' # ('dotted', 'dotted'), # Same as (0, (1, 1)) or '.' # ('dashed', 'dashed'), # Same as '--' # ('dashdot', 'dashdot')] # Same as '-.' linestyle_tuple = [ ('loosely dotted', (0, (1, 10))), ('dotted', (0, (1, 1))), ('densely dotted', (0, (1, 1))), ('loosely dashed', (0, (5, 10))), ('dashed', (0, (5, 5))), ('densely dashed', (0, (5, 1))), ('loosely dashdotted', (0, (3, 10, 1, 10))), ('dashdotted', (0, (3, 5, 1, 5))), ('densely dashdotted', (0, (3, 1, 1, 1))), ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))), ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))), ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))] # color maps for potential and concentration plots cmap_u = plt.get_cmap('Reds') cmap_c = [plt.get_cmap('Oranges'), plt.get_cmap('Blues')] # general line style cycler line_cycler = cycler( linestyle = [ s for _,s in linestyle_tuple ] ) # potential anc concentration cyclers u_cycler = cycler( color = cmap_u( np.linspace(0.4,0.8,N) ) ) u_cycler = len(line_cycler)*u_cycler + len(u_cycler)*line_cycler c_cyclers = [ cycler( color = cmap( np.linspace(0.4,0.8,N) ) ) for cmap in cmap_c ] c_cyclers = [ len(line_cycler)*c_cycler + len(c_cycler)*line_cycler for c_cycler in c_cyclers ] # https://matplotlib.org/3.1.1/tutorials/intermediate/constrainedlayout_guide.html fig, (ax1,ax2,ax3) = plt.subplots( nrows=1, ncols=3, figsize=[24,7], constrained_layout=True) ax1.set_xlabel('z (nm)') ax1.set_ylabel('potential (V)') ax2.set_xlabel('z (nm)') ax2.set_ylabel('concentration (mM)') ax3.set_xlabel('z (nm)') ax3.set_ylabel('concentration (mM)') # ax1.axvline(x=pnp.lambda_D()*1e9, label='Debye Length', color='grey', linestyle=':') species_label = [ '$[\mathrm{Na}^+], ' + param_label + '$', '$[\mathrm{Cl}^-], ' + param_label + '$'] c_regex = re.compile(r'{}_{}'.format(param,scientific_number_regex)) c_graph_handles = [ [] for _ in range(M) ] for f, u_style, c_styles in zip(dat_files,u_cycler,zip(*c_cyclers)): print("Processing {:s}".format(f)) # extract nominal concentration from file name nominal_c = float( c_regex.search(f).group(1) ) dat = np.loadtxt(f,unpack=True) x = dat[0,:] u = dat[1,:] c = dat[2:,:] c_label = '{:> 4.2g}'.format(nominal_c) # potential ax1.plot(x*1e9, u, marker=None, label=c_label, linewidth=1, **u_style) for i in range(c.shape[0]): # concentration ax2.plot(x*1e9, c[i], marker='', label=c_label, linewidth=2, **c_styles[i]) # semilog concentration c_graph_handles[i].extend( ax3.semilogy(x*1e9, c[i], marker='', label=c_label, linewidth=2, **c_styles[i]) ) # legend placement # https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot u_legend = ax1.legend(loc='center right', title='potential, ${}$'.format(param_label), bbox_to_anchor=(-0.2,0.5) ) first_c_legend = ax3.legend(handles=c_graph_handles[0], title=species_label[0], loc='upper left', bbox_to_anchor=(1.00, 1.02) ) second_c_legend = ax3.legend(handles=c_graph_handles[1], title=species_label[1], loc='lower left', bbox_to_anchor=(1.00,-0.02) ) ax3.add_artist(first_c_legend) # add automatically removed first legend again c_legends = [ first_c_legend, second_c_legend ] legends = [ u_legend, *c_legends ] for l in legends: right_align_legend(l) # https://matplotlib.org/3.1.1/tutorials/intermediate/constrainedlayout_guide.html for l in legends: l.set_in_layout(False) # trigger a draw so that constrained_layout is executed once # before we turn it off when printing.... fig.canvas.draw() # we want the legend included in the bbox_inches='tight' calcs. for l in legends: l.set_in_layout(True) # we don't want the layout to change at this point. fig.set_constrained_layout(False) # fig.tight_layout(pad=3.0, w_pad=2.0, h_pad=1.0) # plt.show() fig.savefig(figfile, bbox_inches='tight', dpi=100)
7,482
33.013636
128
py
matscipy
matscipy-master/examples/electrochemistry/pnp_batch/cell_1d/stern_layer_sweep/pnp_plot.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os.path, re, sys import numpy as np from glob import glob from cycler import cycler from itertools import cycle from itertools import groupby import matplotlib.pyplot as plt # Ensure variable is defined try: datadir except NameError: try: datadir = sys.argv[1] except: datadir = 'data' try: figfile except NameError: try: figfile = sys.argv[2] except: figfile = 'fig.png' try: param except NameError: try: param = sys.argv[3] except: param = 'c' try: param_unit except NameError: try: param_label = sys.argv[4] except: param_label = 'c (\mathrm{mM})' try: glob_pattern except NameError: glob_pattern = os.path.join(datadir, 'NaCl*.txt') def right_align_legend(leg): hp = leg._legend_box.get_children()[1] for vp in hp.get_children(): for row in vp.get_children(): row.set_width(100) # need to adapt this manually row.mode= "expand" row.align="right" # sort file names as normal humans expect # https://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python scientific_number_regex = '([-+]?[\d]+\.?[\d]*(?:[Ee][-+]?[\d]+)?)' def alpha_num_order(x): """Sort the given iterable in the way that humans expect.""" def convert(text): try: ret = float(text) # if text.isdigit() else text except: ret = text return ret return [ convert(c) for c in re.split(scientific_number_regex, x) ] dat_files = sorted(glob(glob_pattern),key=alpha_num_order) N = len(dat_files) # number of data sets M = 2 # number of species # matplotlib settings SMALL_SIZE = 8 MEDIUM_SIZE = 12 BIGGER_SIZE = 16 # plt.rc('axes', prop_cycle=default_cycler) plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure titlex plt.rcParams["figure.figsize"] = (16,10) # the standard figure size plt.rcParams["lines.linewidth"] = 3 plt.rcParams["lines.markersize"] = 14 plt.rcParams["lines.markeredgewidth"]=1 # line styles # https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html # linestyle_str = [ # ('solid', 'solid'), # Same as (0, ()) or '-' # ('dotted', 'dotted'), # Same as (0, (1, 1)) or '.' # ('dashed', 'dashed'), # Same as '--' # ('dashdot', 'dashdot')] # Same as '-.' linestyle_tuple = [ ('loosely dotted', (0, (1, 10))), ('dotted', (0, (1, 1))), ('densely dotted', (0, (1, 1))), ('loosely dashed', (0, (5, 10))), ('dashed', (0, (5, 5))), ('densely dashed', (0, (5, 1))), ('loosely dashdotted', (0, (3, 10, 1, 10))), ('dashdotted', (0, (3, 5, 1, 5))), ('densely dashdotted', (0, (3, 1, 1, 1))), ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))), ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))), ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))] # color maps for potential and concentration plots cmap_u = plt.get_cmap('Reds') cmap_c = [plt.get_cmap('Oranges'), plt.get_cmap('Blues')] # general line style cycler line_cycler = cycler( linestyle = [ s for _,s in linestyle_tuple ] ) # potential anc concentration cyclers u_cycler = cycler( color = cmap_u( np.linspace(0.4,0.8,N) ) ) u_cycler = len(line_cycler)*u_cycler + len(u_cycler)*line_cycler c_cyclers = [ cycler( color = cmap( np.linspace(0.4,0.8,N) ) ) for cmap in cmap_c ] c_cyclers = [ len(line_cycler)*c_cycler + len(c_cycler)*line_cycler for c_cycler in c_cyclers ] # https://matplotlib.org/3.1.1/tutorials/intermediate/constrainedlayout_guide.html fig, (ax1,ax2,ax3) = plt.subplots( nrows=1, ncols=3, figsize=[24,7], constrained_layout=True) ax1.set_xlabel('z (nm)') ax1.set_ylabel('potential (V)') ax2.set_xlabel('z (nm)') ax2.set_ylabel('concentration (mM)') ax3.set_xlabel('z (nm)') ax3.set_ylabel('concentration (mM)') # ax1.axvline(x=pnp.lambda_D()*1e9, label='Debye Length', color='grey', linestyle=':') species_label = [ '$[\mathrm{Na}^+], ' + param_label + '$', '$[\mathrm{Cl}^-], ' + param_label + '$'] c_regex = re.compile(r'{}_{}'.format(param,scientific_number_regex)) c_graph_handles = [ [] for _ in range(M) ] for f, u_style, c_styles in zip(dat_files,u_cycler,zip(*c_cyclers)): print("Processing {:s}".format(f)) # extract nominal concentration from file name nominal_c = float( c_regex.search(f).group(1) ) dat = np.loadtxt(f,unpack=True) x = dat[0,:] u = dat[1,:] c = dat[2:,:] c_label = '{:> 4.2g}'.format(nominal_c) # potential ax1.plot(x*1e9, u, marker=None, label=c_label, linewidth=1, **u_style) for i in range(c.shape[0]): # concentration ax2.plot(x*1e9, c[i], marker='', label=c_label, linewidth=2, **c_styles[i]) # semilog concentration c_graph_handles[i].extend( ax3.semilogy(x*1e9, c[i], marker='', label=c_label, linewidth=2, **c_styles[i]) ) # legend placement # https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot u_legend = ax1.legend(loc='center right', title='potential, ${}$'.format(param_label), bbox_to_anchor=(-0.2,0.5) ) first_c_legend = ax3.legend(handles=c_graph_handles[0], title=species_label[0], loc='upper left', bbox_to_anchor=(1.00, 1.02) ) second_c_legend = ax3.legend(handles=c_graph_handles[1], title=species_label[1], loc='lower left', bbox_to_anchor=(1.00,-0.02) ) ax3.add_artist(first_c_legend) # add automatically removed first legend again c_legends = [ first_c_legend, second_c_legend ] legends = [ u_legend, *c_legends ] for l in legends: right_align_legend(l) # https://matplotlib.org/3.1.1/tutorials/intermediate/constrainedlayout_guide.html for l in legends: l.set_in_layout(False) # trigger a draw so that constrained_layout is executed once # before we turn it off when printing.... fig.canvas.draw() # we want the legend included in the bbox_inches='tight' calcs. for l in legends: l.set_in_layout(True) # we don't want the layout to change at this point. fig.set_constrained_layout(False) # fig.tight_layout(pad=3.0, w_pad=2.0, h_pad=1.0) # plt.show() fig.savefig(figfile, bbox_inches='tight', dpi=100)
7,482
33.013636
128
py
matscipy
matscipy-master/examples/electrochemistry/pnp_batch/cell_1d/concentration_sweep/pnp_plot.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os.path, re, sys import numpy as np from glob import glob from cycler import cycler from itertools import cycle from itertools import groupby import matplotlib.pyplot as plt # Ensure variable is defined try: datadir except NameError: try: datadir = sys.argv[1] except: datadir = 'data' try: figfile except NameError: try: figfile = sys.argv[2] except: figfile = 'fig.png' try: param except NameError: try: param = sys.argv[3] except: param = 'c' try: param_unit except NameError: try: param_label = sys.argv[4] except: param_label = 'c (\mathrm{mM})' try: glob_pattern except NameError: glob_pattern = os.path.join(datadir, 'NaCl*.txt') def right_align_legend(leg): hp = leg._legend_box.get_children()[1] for vp in hp.get_children(): for row in vp.get_children(): row.set_width(100) # need to adapt this manually row.mode= "expand" row.align="right" # sort file names as normal humans expect # https://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python def alpha_num_order(x): """Sort the given iterable in the way that humans expect.""" convert = lambda text: int(text) if text.isdigit() else text return [ convert(c) for c in re.split('([0-9]+)', x) ] dat_files = sorted(glob(glob_pattern),key=alpha_num_order) N = len(dat_files) # number of data sets M = 2 # number of species # matplotlib settings SMALL_SIZE = 8 MEDIUM_SIZE = 12 BIGGER_SIZE = 16 # plt.rc('axes', prop_cycle=default_cycler) plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure titlex plt.rcParams["figure.figsize"] = (16,10) # the standard figure size plt.rcParams["lines.linewidth"] = 3 plt.rcParams["lines.markersize"] = 14 plt.rcParams["lines.markeredgewidth"]=1 # line styles # https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html # linestyle_str = [ # ('solid', 'solid'), # Same as (0, ()) or '-' # ('dotted', 'dotted'), # Same as (0, (1, 1)) or '.' # ('dashed', 'dashed'), # Same as '--' # ('dashdot', 'dashdot')] # Same as '-.' linestyle_tuple = [ ('loosely dotted', (0, (1, 10))), ('dotted', (0, (1, 1))), ('densely dotted', (0, (1, 1))), ('loosely dashed', (0, (5, 10))), ('dashed', (0, (5, 5))), ('densely dashed', (0, (5, 1))), ('loosely dashdotted', (0, (3, 10, 1, 10))), ('dashdotted', (0, (3, 5, 1, 5))), ('densely dashdotted', (0, (3, 1, 1, 1))), ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))), ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))), ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))] # color maps for potential and concentration plots cmap_u = plt.get_cmap('Reds') cmap_c = [plt.get_cmap('Oranges'), plt.get_cmap('Blues')] # general line style cycler line_cycler = cycler( linestyle = [ s for _,s in linestyle_tuple ] ) # potential anc concentration cyclers u_cycler = cycler( color = cmap_u( np.linspace(0.4,0.8,N) ) ) u_cycler = len(line_cycler)*u_cycler + len(u_cycler)*line_cycler c_cyclers = [ cycler( color = cmap( np.linspace(0.4,0.8,N) ) ) for cmap in cmap_c ] c_cyclers = [ len(line_cycler)*c_cycler + len(c_cycler)*line_cycler for c_cycler in c_cyclers ] # https://matplotlib.org/3.1.1/tutorials/intermediate/constrainedlayout_guide.html fig, (ax1,ax2,ax3) = plt.subplots( nrows=1, ncols=3, figsize=[24,7], constrained_layout=True) ax1.set_xlabel('z (nm)') ax1.set_ylabel('potential (V)') ax2.set_xlabel('z (nm)') ax2.set_ylabel('concentration (mM)') ax3.set_xlabel('z (nm)') ax3.set_ylabel('concentration (mM)') # ax1.axvline(x=pnp.lambda_D()*1e9, label='Debye Length', color='grey', linestyle=':') species_label = [ '$[\mathrm{Na}^+], ' + param_label + '$', '$[\mathrm{Cl}^-], ' + param_label + '$'] c_regex = re.compile(r'{}_(-?\d+(,\d+)*(\.\d+(e\d+)?)?)'.format(param)) c_graph_handles = [ [] for _ in range(M) ] for f, u_style, c_styles in zip(dat_files,u_cycler,zip(*c_cyclers)): print("Processing {:s}".format(f)) # extract nominal concentration from file name nominal_c = float( c_regex.search(f).group(1) ) dat = np.loadtxt(f,unpack=True) x = dat[0,:] u = dat[1,:] c = dat[2:,:] c_label = '{:> 4.1f}'.format(nominal_c) # potential ax1.plot(x*1e9, u, marker=None, label=c_label, linewidth=1, **u_style) for i in range(c.shape[0]): # concentration ax2.plot(x*1e9, c[i], marker='', label=c_label, linewidth=2, **c_styles[i]) # semilog concentration c_graph_handles[i].extend( ax3.semilogy(x*1e9, c[i], marker='', label=c_label, linewidth=2, **c_styles[i]) ) # legend placement # https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot u_legend = ax1.legend(loc='center right', title='potential, ${}$'.format(param_label), bbox_to_anchor=(-0.2,0.5) ) first_c_legend = ax3.legend(handles=c_graph_handles[0], title=species_label[0], loc='upper left', bbox_to_anchor=(1.00, 1.02) ) second_c_legend = ax3.legend(handles=c_graph_handles[1], title=species_label[1], loc='lower left', bbox_to_anchor=(1.00,-0.02) ) ax3.add_artist(first_c_legend) # add automatically removed first legend again c_legends = [ first_c_legend, second_c_legend ] legends = [ u_legend, *c_legends ] for l in legends: right_align_legend(l) # https://matplotlib.org/3.1.1/tutorials/intermediate/constrainedlayout_guide.html for l in legends: l.set_in_layout(False) # trigger a draw so that constrained_layout is executed once # before we turn it off when printing.... fig.canvas.draw() # we want the legend included in the bbox_inches='tight' calcs. for l in legends: l.set_in_layout(True) # we don't want the layout to change at this point. fig.set_constrained_layout(False) # fig.tight_layout(pad=3.0, w_pad=2.0, h_pad=1.0) # plt.show() fig.savefig(figfile, bbox_inches='tight', dpi=100)
7,314
33.342723
128
py
matscipy
matscipy-master/examples/distributed_computation/distributed_client.py
# # Copyright 2015 Lars Pastewka (U. Freiburg) # 2015 Till Junge (EPFL) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """ @file DistributedClient.py @author Till Junge <[email protected]> @date 19 Mar 2015 @brief example for using the multiprocessing capabilities of PyPyContact ported for matscipy, clientside @section LICENCE Copyright (C) 2015 Till Junge DistributedClient.py 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, or (at your option) any later version. DistributedClient.py 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 GNU Emacs; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ from matscipy import BaseWorker class Worker(BaseWorker): def __init__(self, address, port, key, worker_id): super(Worker, self).__init__(address, port, key.encode()) self.worker_id = worker_id def process(self, job_description, job_id): self.result_queue.put((self.worker_id, job_id)) def parse_args(): parser = Worker.get_arg_parser() parser.add_argument('id', metavar='WORKER-ID', type=int, help='Identifier for this process') args = parser.parse_args() return args def main(): args = parse_args() worker = Worker(args.server_address, args.port, args.auth_token, args.id) worker.daemon = True worker.start() while not worker.work_done_flag.is_set(): worker.job_queue.join() if __name__ == "__main__": main()
2,588
30.573171
96
py
matscipy
matscipy-master/examples/distributed_computation/distributed_server.py
# # Copyright 2015 Lars Pastewka (U. Freiburg) # 2015 Till Junge (EPFL) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """ @file DistributedServer.py @author Till Junge <[email protected]> @date 19 Mar 2015 @brief example for using the multiprocessing capabilities of PyPyContact ported for matscipy, serverside @section LICENCE Copyright (C) 2015 Till Junge DistributedServer.py 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, or (at your option) any later version. DistributedServer.py 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 GNU Emacs; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ from matscipy import BaseResultManager import numpy as np class Manager(BaseResultManager): def __init__(self, port, key, resolution): super(Manager, self).__init__(port, key.encode()) self.resolution = resolution center_coord = (resolution[0]//2, resolution[1]//2) initial_guess = 1 self.available_jobs = dict({center_coord: initial_guess}) self.scheduled = set() self.done_jobs = set() self.set_todo_counter(np.prod(resolution)) self.result_matrix = np.zeros(resolution) def schedule_available_jobs(self): for coords, init_guess in self.available_jobs.items(): dummy_offset = 1 self.job_queue.put(((init_guess, dummy_offset), coords)) self.scheduled.add(coords) self.available_jobs.clear() def mark_ready(self, i, j, initial_guess): if (i, j) not in self.available_jobs.keys() and (i, j) not in self.scheduled: self.available_jobs[(i, j)] = initial_guess def process(self, value, coords): i, j = coords self.result_matrix[i, j] = value self.decrement_todo_counter() print("got solution to job '{}', {} left to do".format( (i, j), self.get_todo_counter())) self.done_jobs.add((i, j)) if self.get_todo_counter() < 10: print("Missing jobs: {}".format(self.scheduled-self.done_jobs)) #tag neighbours as available if i > 0: self.mark_ready(i-1, j, value) if j > 0: self.mark_ready(i, j-1, value) if i < self.resolution[0]-1: self.mark_ready(i+1, j, value) if j < self.resolution[1]-1: self.mark_ready(i, j+1, value) def parse_args(): parser = Manager.get_arg_parser() args = parser.parse_args() return args def main(): args = parse_args() manager = Manager(args.port, args.auth_token, (12, 12)) manager.run() if __name__ == "__main__": main()
3,787
32.522124
95
py
matscipy
matscipy-master/examples/glasses/amorphous_SiC/params.py
# # Copyright 2016 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import atomistica # Quick and robust calculator to relax initial positions quick_calc = atomistica.Tersoff() # Calculator for actual quench calc = atomistica.TersoffScr() stoichiometry = 'Si128C128' densities = [3.21]
1,009
33.827586
71
py
matscipy
matscipy-master/examples/mcfm/simulation_setup.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2018 Jacek Golebiowski (Imperial College London) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """This script sets up a simulation of a 10 monomer polypropylene chain""" import numpy as np import ase.io from utilities import MorsePotentialPerAtom from matscipy.calculators.mcfm.neighbour_list_mcfm.neighbour_list_mcfm import NeighbourListMCFM from matscipy.calculators.mcfm.qm_cluster import QMCluster from matscipy.calculators.mcfm.calculator import MultiClusterForceMixingPotential def load_atoms(filename): """Load atoms from the file""" atoms = ase.io.read(filename, index=0, format="extxyz") atoms.arrays["atomic_index"] = np.arange(len(atoms)) return atoms def create_neighbour_list(atoms): """Create the neighbour list""" hysteretic_cutoff_break_factor = 3 cutoffs = dict() c_helper = dict(H=0.7, C=1, N=1, O=1) for keyi in c_helper: for keyj in c_helper: cutoffs[(keyi, keyj)] = c_helper[keyi] + c_helper[keyj] neighbour_list = NeighbourListMCFM(atoms, cutoffs, skin=0.3, hysteretic_break_factor=hysteretic_cutoff_break_factor) neighbour_list.update(atoms) return neighbour_list def create_mcfm_potential(atoms, classical_calculator=None, qm_calculator=None, special_atoms_list=None, double_bonded_atoms_list=None ): """Set up a multi cluster force mixing potential with a sensible set of defaults Parameters ---------- atoms : ASE.atoms atoms object classical_calculator : AE.calculator classical calculator qm_calculator : ASE.calculator qm calculator special_atoms_list : list of ints (atomic indices) In case a group of special atoms are specified (special molecule), If one of these atoms is in the buffer region, the rest are also added to it. double_bonded_atoms_list : list list of doubly bonded atoms for the clustering module, needed for double hydrogenation. Returns ------- MultiClusterForceMixingPotential ase.calculator supporting hybrid simulations. """ if special_atoms_list is None: special_atoms_list = [[]] if double_bonded_atoms_list is None: double_bonded_atoms_list = [] ######################################################################## # Stage 1 - Neighbour List routines ######################################################################## neighbour_list = create_neighbour_list(atoms) ######################################################################## # Stage 1 - Set up QM clusters ######################################################################## qm_flag_potential_energies = np.ones((len(atoms), 2), dtype=float) * 100 atoms.arrays["qm_flag_potential_energies[in_out]"] = qm_flag_potential_energies.copy() qm_cluster = QMCluster(special_atoms_list=special_atoms_list, verbose=0) qm_cluster.attach_neighbour_list(neighbour_list) qm_cluster.attach_flagging_module(qm_flag_potential_energies=qm_flag_potential_energies, small_cluster_hops=3, only_heavy=False, ema_parameter=0.01, energy_cap=1000, energy_increase=1) qm_cluster.attach_clustering_module(double_bonded_atoms_list=double_bonded_atoms_list) ######################################################################## # Stage 1 - Set Up the multi cluster force mixing potential ######################################################################## mcfm_pot = MultiClusterForceMixingPotential(atoms=atoms, classical_calculator=classical_calculator, qm_calculator=qm_calculator, qm_cluster=qm_cluster, forced_qm_list=None, change_bonds=True, calculate_errors=False, calculation_always_required=False, buffer_hops=6, verbose=0, enable_check_state=True ) mcfm_pot.debug_qm = False mcfm_pot.conserve_momentum = True # ------ Parallel module makes this simple simulation extremely slow # ------ Due ot large overhead. Use only with QM potentials mcfm_pot.doParallel = False atoms.set_calculator(mcfm_pot) return mcfm_pot def main(): atoms = load_atoms("structures/carbon_chain.xyz") nl = create_neighbour_list(atoms) for idx in range(15): print("Atom: {}, neighbours: {}".format(idx, nl.neighbours[idx])) print("[") for idx in range(len(atoms)): print("np.{},".format(repr(nl.neighbours[idx]))) print("]") morse1 = MorsePotentialPerAtom(r0=2, epsilon=2, rho0=6) morse2 = MorsePotentialPerAtom(r0=2, epsilon=4, rho0=6) mcfm_pot = create_mcfm_potential(atoms, classical_calculator=morse1, qm_calculator=morse2, special_atoms_list=None, double_bonded_atoms_list=None) if (__name__ == "__main__"): main()
6,653
38.607143
95
py
matscipy
matscipy-master/examples/mcfm/example_simulation.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2018 Jacek Golebiowski (Imperial College London) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """This script sets up a simulation of a 10 monomer polypropylene chain""" import numpy as np import ase.io import ase.units as units import ase.constraints from ase.optimize import FIRE from utilities import (MorsePotentialPerAtom, LinearConstraint, trajectory_writer, mcfm_thermo_printstatus, mcfm_error_logger) from simulation_setup import load_atoms, create_neighbour_list, create_mcfm_potential from ase.md.langevin import Langevin from ase.md.velocitydistribution import MaxwellBoltzmannDistribution def get_dynamics(atoms, mcfm_pot, T=300): # ------ Set up logfiles traj_interval = 10 thermoPrintstatus_log = open("log_thermoPrintstatus.log", "w") outputTrajectory = open("log_trajectory.xyz", "w") mcfmError_log = open("log_mcfmError.log", "w") # ------ Let optimiser use the base potential and relax the per atom energies mcfm_pot.qm_cluster.flagging_module.ema_parameter = 0.1 mcfm_pot.qm_cluster.flagging_module.qm_flag_potential_energies =\ np.ones((len(atoms), 2), dtype=float) * 1001 # ------ Minimize positions opt = FIRE(atoms) optimTrajectory = open("log_optimizationTrajectory.xyz", "w") opt.attach(trajectory_writer, 1, atoms, optimTrajectory, writeResults=True) opt.run(fmax=0.05, steps=1000) # ------ Define ASE dyamics sim_T = T * units.kB MaxwellBoltzmannDistribution(atoms, 2 * sim_T) timestep = 5e-1 * units.fs friction = 1e-2 dynamics = Langevin(atoms, timestep, sim_T, friction, fixcm=False) dynamics.attach(mcfm_thermo_printstatus, 100, 100, dynamics, atoms, mcfm_pot, logfile=thermoPrintstatus_log) dynamics.attach(trajectory_writer, traj_interval, atoms, outputTrajectory, writeResults=False) dynamics.attach(mcfm_error_logger, 100, 100, dynamics, atoms, mcfm_pot, logfile=mcfmError_log) return dynamics def main(): atoms = load_atoms("structures/carbon_chain.xyz") morse1 = MorsePotentialPerAtom(r0=3, epsilon=2, rho0=6) morse2 = MorsePotentialPerAtom(r0=3, epsilon=4, rho0=6) mcfm_pot = create_mcfm_potential(atoms, classical_calculator=morse1, qm_calculator=morse2, special_atoms_list=None, double_bonded_atoms_list=None) dynamics = get_dynamics(atoms, mcfm_pot, T=100) # ------ Add constraints fixed = 29 moving = 1 direction = np.array([0, 0, 1]) velocity = 5e-4 * units.Ang c_fixed = ase.constraints.FixAtoms([fixed]) c_relax = ase.constraints.FixAtoms([moving]) c_moving = LinearConstraint(moving, direction, velocity) atoms.set_constraint([c_fixed, c_moving]) # ------ Adjust flagging energies mcfm_pot.qm_cluster.flagging_module.ema_parameter = 0.003 mcfm_pot.qm_cluster.flagging_module.qm_flag_potential_energies =\ np.ones((len(atoms), 2), dtype=float) mcfm_pot.qm_cluster.flagging_module.qm_flag_potential_energies[:, 0] *= -5 mcfm_pot.qm_cluster.flagging_module.qm_flag_potential_energies[:, 1] *= -6 atoms.arrays["qm_flag_potential_energies[in_out]"] =\ mcfm_pot.qm_cluster.flagging_module.qm_flag_potential_energies # ------ Run dynamics dynamics.run(14000) atoms.set_constraint([c_fixed, c_relax]) dynamics.run(3000) if (__name__ == "__main__"): main()
4,277
37.196429
98
py
matscipy
matscipy-master/examples/mcfm/utilities.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2018 Jacek Golebiowski (Imperial College London) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # """Copy of ASE Morse calculator that supports per-atom potential energy. Also extra utilities""" import numpy as np from math import exp, sqrt import ase.io import ase.units as units from ase.calculators.calculator import Calculator from ase.constraints import FixConstraintSingle class MorsePotentialPerAtom(Calculator): """Morse potential. Default values chosen to be similar as Lennard-Jones. """ implemented_properties = ['energy', 'forces', 'potential_energies'] default_parameters = {'epsilon': 1.0, 'rho0': 6.0, 'r0': 1.0} nolabel = True def __init__(self, **kwargs): Calculator.__init__(self, **kwargs) def calculate(self, atoms=None, properties=['energy'], system_changes=['positions', 'numbers', 'cell', 'pbc', 'charges', 'magmoms']): Calculator.calculate(self, atoms, properties, system_changes) epsilon = self.parameters.epsilon rho0 = self.parameters.rho0 r0 = self.parameters.r0 positions = self.atoms.get_positions() energy = 0.0 energies = np.zeros(len(self.atoms)) forces = np.zeros((len(self.atoms), 3)) preF = 2 * epsilon * rho0 / r0 for i1, p1 in enumerate(positions): for i2, p2 in enumerate(positions[:i1]): diff = p2 - p1 r = sqrt(np.dot(diff, diff)) expf = exp(rho0 * (1.0 - r / r0)) energy += epsilon * expf * (expf - 2) energies[i1] += epsilon * expf * (expf - 2) energies[i2] += epsilon * expf * (expf - 2) F = preF * expf * (expf - 1) * diff / r forces[i1] -= F forces[i2] += F self.results['energy'] = energy self.results['forces'] = forces self.results['potential_energies'] = energies def trajectory_writer(atoms, outputFile, writeResults=False): ase.io.write(outputFile, atoms, format="extxyz", write_results=writeResults) outputFile.flush() def mcfm_thermo_printstatus(frequency, dynamics, atoms, potential, logfile=None): """Thermodynamicsal data printout""" if dynamics.nsteps == frequency: header = "%5.5s %16.15s %16.15s %16.15s %16.15s %16.15s :thermo\n" % ( "nsteps", "temperature", "potential_E", "kinetic_E", "total_E", "QM_atoms_no") if logfile is not None: logfile.write(header) logfile.flush() print(header) if "energy" in potential.classical_calculator.results: potential_energy = potential.classical_calculator.results["energy"] elif "potential_energy" in potential.classical_calculator.results: potential_energy = potential.classical_calculator.results["potential_energy"] else: potential_energy = potential.get_potential_energy(atoms) kinetic_energy = atoms.get_kinetic_energy() total_energy = potential_energy + kinetic_energy temp = kinetic_energy / (1.5 * units.kB * len(atoms)) full_qm_atoms_no = len([item for sublist in potential.cluster_list for item in sublist]) log = "%5.1f %16.5e %16.5e %16.5e %16.5e %5.0f :thermo" % ( dynamics.nsteps, temp, potential_energy, kinetic_energy, total_energy, full_qm_atoms_no, ) if logfile is not None: logfile.write(log + "\n") logfile.flush() print(log) def mcfm_error_logger(frequency, dynamics, atoms, mcfm_pot, logfile=None): """This is the logger for mcfm potential to be used with a DS simulation""" # Evaluate errors mcfm_pot.evaluate_errors(atoms, heavy_only=True) # Print output if dynamics.nsteps == frequency: header = "%5.5s %16.10s %16.10s %16.10s %16.10s %16.10s %16.10s %16.10s :errLog\n" % ( "nsteps", "MAX_abs_fe", "RMS_abs_fe", "MAX_rel_fe", "RMS_rel_fe", "cumulFError", "cumEcontribution", "n_QM_atoms") if logfile is not None: logfile.write(header) logfile.flush() log = "%5.1f %16.5e %16.5e %16.5e %16.5e %16.5e %16.5e %16.0f :errLog" % ( dynamics.nsteps, mcfm_pot.errors["max absolute error"], mcfm_pot.errors["rms absolute error"], mcfm_pot.errors["max relative error"], mcfm_pot.errors["rms relative error"], np.mean(mcfm_pot.errors["Cumulative fError vector length"]), mcfm_pot.errors["Cumulative energy change"], mcfm_pot.errors["no of QM atoms"] ) if logfile is not None: logfile.write(log + "\n") logfile.flush() if (len(mcfm_pot.cluster_list) > 0): print("\tAbs errors:= RMS: %0.5f, MAX: %0.5f\t Rel errors:= RMS: %0.5f, MAX: %0.5f :errLog" % (mcfm_pot.errors["rms absolute error"], mcfm_pot.errors["max absolute error"], mcfm_pot.errors["rms relative error"], mcfm_pot.errors["max relative error"])) class LinearConstraint(FixConstraintSingle): """Constrain an atom to move along a given direction only.""" def __init__(self, a, direction, velocity): self.a = a self.dir = direction / np.sqrt(np.dot(direction, direction)) self.velo = velocity self.removed_dof = 0 def adjust_positions(self, atoms, newpositions): step = self.dir * self.velo newpositions[self.a] = atoms.positions[self.a] + step def adjust_forces(self, atoms, forces): forces[self.a] = np.zeros(3) def __repr__(self): return 'LinearConstraint(%d, %s, %.2e)' % (self.a, self.dir.tolist(), self.velo) def todict(self): return {'name': 'LinearConstraint', 'kwargs': {'a': self.a, 'direction': self.dir, "velocity": self.velo}}
6,800
34.238342
101
py
matscipy
matscipy-master/scripts/average_eam_potential.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2020 Wolfram G. Nöhring (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import numpy as np import click from matscipy.calculators.eam import io, average_atom @click.command() @click.argument("input_table", type=click.Path(exists=True, readable=True)) @click.argument("output_table", type=click.Path(exists=False, writable=True)) @click.argument("concentrations", nargs=-1) def average(input_table, output_table, concentrations): """Create Average-atom potential for an Embedded Atom Method potential Read an EAM potential from INPUT_TABLE, create the Average-atom potential for the random alloy with composition specified by CONCENTRATIONS and write a new table with both the original and the A-atom potential functions to OUTPUT_TABLE. CONCENTRATIONS is a whitespace-separated list of the concentration of the elements, in the order in which the appear in the input table. """ source, parameters, F, f, rep = io.read_eam(input_table) (new_parameters, new_F, new_f, new_rep) = average_atom.average_potential( np.array(concentrations, dtype=float), parameters, F, f, rep ) composition = " ".join( [str(c * 100.0) + f"% {e}," for c, e in zip(np.array(concentrations, dtype=float), parameters.symbols)] ) composition = composition.rstrip(",") source += f", averaged for composition {composition}" io.write_eam( source, new_parameters, new_F, new_f, new_rep, output_table, kind="eam/alloy", ) if __name__ == "__main__": average()
2,343
36.206349
111
py
matscipy
matscipy-master/scripts/openovito.py
# # Copyright 2015 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import sys sys.stdout = open('stdout.txt', 'w') sys.stderr = open('stderr.txt', 'w') import numpy as np from ovito import * from ovito.data import * from ovito.modifiers import * import ase2ovito from ase.io import read, write # Read ASE Atoms instance from disk atoms = read(sys.argv[1]) # add some comuted properties atoms.new_array('real', (atoms.positions**2).sum(axis=1)) atoms.new_array('int', np.array([-1]*len(atoms))) # convert from Atoms to DataCollection data = DataCollection.create_from_atoms(atoms) # Create a node and insert it into the scene node = ObjectNode() node.source = data dataset.scene_nodes.append(node) # add some bonds bonds = ase2ovito.neighbours_to_bonds(atoms, 2.5) print 'Bonds:' print bonds.array data.add(bonds) # alternatively, ask Ovito to create the bonds #node.modifiers.append(CreateBondsModifier(cutoff=2.5)) new_data = node.compute() #print new_data.bonds.array # Select the new node and adjust viewport cameras to show everything. dataset.selected_node = node for vp in dataset.viewports: vp.zoom_all() # Do the reverse conversion, after pipeline has been applied atoms = new_data.to_atoms() # Dump results to disk atoms.write('dump.extxyz')
1,997
26
71
py
matscipy
matscipy-master/scripts/ase2ovito.py
# # Copyright 2015 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import numpy as np from ovito.data import (DataCollection, SimulationCell, ParticleProperty, ParticleType, Bonds) from ase.atoms import Atoms from matscipy.neighbours import neighbour_list def datacollection_to_atoms(self): """ Convert from ovito.data.DataCollection to ase.atoms.Atoms """ # Extract basic dat: pbc, cell, positions, particle types pbc = self.cell.pbc cell_matrix = np.array(self.cell.matrix) cell, origin = cell_matrix[:, :3], cell_matrix[:, 3] info = {'cell_origin': origin } positions = np.array(self.position) type_names = dict([(t.id, t.name) for t in self.particle_type.type_list]) symbols = [type_names[id] for id in np.array(self.particle_type)] # construct ase.Atoms object atoms = Atoms(symbols, positions, cell=cell, pbc=pbc, info=info) # Convert any other particle properties to additional arrays for name, prop in self.iteritems(): if name in ['Simulation cell', 'Position', 'Particle Type']: continue if not isinstance(prop, ParticleProperty): continue atoms.new_array(prop.name, prop.array) return atoms DataCollection.to_atoms = datacollection_to_atoms def datacollection_create_from_atoms(cls, atoms): """ Convert from ase.atoms.Atoms to ovito.data.DataCollection """ data = cls() # Set the unit cell and origin (if specified in atoms.info) cell = SimulationCell() matrix = np.zeros((3,4)) matrix[:, :3] = atoms.get_cell() matrix[:, 3] = atoms.info.get('cell_origin', [0., 0., 0.]) cell.matrix = matrix cell.pbc = [bool(p) for p in atoms.get_pbc()] data.add(cell) # Add ParticleProperty from atomic positions num_particles = len(atoms) position = ParticleProperty.create(ParticleProperty.Type.Position, num_particles) position.mutable_array[...] = atoms.get_positions() data.add(position) # Set particle types from chemical symbols types = ParticleProperty.create(ParticleProperty.Type.ParticleType, num_particles) symbols = atoms.get_chemical_symbols() type_list = list(set(symbols)) for i, sym in enumerate(type_list): types.type_list.append(ParticleType(id=i+1, name=sym)) types.mutable_array[:] = [ type_list.index(sym)+1 for sym in symbols ] data.add(types) # Add other properties from atoms.arrays for name, array in atoms.arrays.iteritems(): if name in ['positions', 'numbers']: continue if array.dtype.kind == 'i': typ = 'int' elif array.dtype.kind == 'f': typ = 'float' else: continue num_particles = array.shape[0] num_components = 1 if len(array.shape) == 2: num_components = array.shape[1] prop = ParticleProperty.create_user(name, typ, num_particles, num_components) prop.mutable_array[...] = array data.add(prop) return data DataCollection.create_from_atoms = classmethod(datacollection_create_from_atoms) def neighbours_to_bonds(atoms, cutoff): i, j = neighbour_list('ij', atoms, cutoff) bonds = Bonds() for ii, jj in zip(i, j): bonds.add_full(int(ii), int(jj)) return bonds
4,546
32.932836
80
py
matscipy
matscipy-master/scripts/fracture_mechanics/cohesive_stress.py
# # Copyright 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import os import sys import numpy as np import ase import ase.constraints import ase.io import ase.optimize from ase.data import atomic_numbers from ase.parallel import parprint ### sys.path += [ "." ] import params ### cryst = params.cryst.copy() cryst.set_calculator(params.calc) cryst.info['energy'] = cryst.get_potential_energy() ase.io.write('cryst.xyz', cryst, format='extxyz') # The bond we will open up bond1, bond2 = params.bond # Run strain calculation. for i, separation in enumerate(params.separations): parprint('=== separation = {0} ==='.format(separation)) xyz_file = 'separation_%04d.xyz' % int(separation*1000) if os.path.exists(xyz_file): parprint('%s found, skipping' % xyz_file) a = ase.io.read(xyz_file) a.set_calculator(params.calc) else: a = cryst.copy() cell = a.cell.copy() cell[1,1] += separation a.set_cell(cell, scale_atoms=False) # Assign calculator. a.set_calculator(params.calc) a.set_constraint(None) a.info['separation'] = separation a.info['bond_length'] = a.get_distance(bond1, bond2, mic=True) a.info['energy'] = a.get_potential_energy() a.info['cell_origin'] = [0, 0, 0] ase.io.write(xyz_file, a, format='extxyz') # Relax the final surface configuration parprint('Optimizing final positions...') opt = ase.optimize.FIRE(a, logfile=None) opt.run(fmax=params.fmax) parprint('...done. Converged within {0} steps.' \ .format(opt.get_number_of_steps())) a.set_constraint(None) a.set_array('forces', a.get_forces()) a.info['separation'] = separation a.info['energy'] = a.get_potential_energy() a.info['cell_origin'] = [0, 0, 0] a.info['bond_length'] = a.get_distance(bond1, bond2, mic=True) ase.io.write('surface.xyz', a, format='extxyz')
3,620
32.527778
72
py
matscipy
matscipy-master/scripts/fracture_mechanics/sinclair_approx.py
# # Copyright 2020 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import sys import numpy as np from ase.units import GPa from matscipy import parameter from matscipy.elasticity import fit_elastic_constants from matscipy.fracture_mechanics.crack import CubicCrystalCrack, SinclairCrack from scipy.optimize import fsolve sys.path.insert(0, '.') import params calc = parameter('calc') fmax = parameter('fmax', 1e-3) max_steps = parameter('max_steps', 100) vacuum = parameter('vacuum', 10.0) alpha_scale = parameter('alpha_scale', 1.0) continuation = parameter('continuation', False) ds = parameter('ds', 1e-2) nsteps = parameter('nsteps', 10) method = parameter('method', 'full') k0 = parameter('k0', 1.0) # compute elastic constants cryst = params.cryst.copy() cryst.pbc = True cryst.calc = calc C, C_err = fit_elastic_constants(cryst, symmetry=parameter('elastic_symmetry', 'triclinic')) crk = CubicCrystalCrack(parameter('crack_surface'), parameter('crack_front'), Crot=C/GPa) # Get Griffith's k1. k1g = crk.k1g(parameter('surface_energy')) print('Griffith k1 = %f' % k1g) cluster = params.cluster.copy() sc = SinclairCrack(crk, cluster, calc, k0 * k1g, vacuum=vacuum, alpha_scale=alpha_scale) mask = sc.regionI | sc.regionII extended_far_field = parameter('extended_far_field', False) if extended_far_field: mask = sc.regionI | sc.regionII | sc.regionIII def f(k, alpha): sc.k = k * k1g sc.alpha = alpha sc.update_atoms() return sc.get_crack_tip_force( mask=mask) alpha_range = parameter('alpha_range', np.linspace(-1.0, 1.0, 100)) # look for a solution to f(k, alpha) = 0 close to alpha = 0. k = k0 # initial guess for k traj = [] for alpha in alpha_range: (k,) = fsolve(f, k, args=(alpha,)) print(f'alpha={alpha:.3f} k={k:.3f} ') traj.append((alpha, k)) np.savetxt('traj_approximate.txt', traj)
2,730
29.685393
78
py
matscipy
matscipy-master/scripts/fracture_mechanics/quartz_crack.py
# # Copyright 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os import sys import numpy as np from ase.atoms import Atoms from ase.io import read, write from ase.calculators.neighborlist import NeighborList from ase.units import GPa, J, m from ase.optimize import FIRE from matscipy.elasticity import measure_triclinic_elastic_constants import matscipy.fracture_mechanics.crack as crack sys.path.insert(0, '.') import params print 'Fixed %d atoms' % (g==0).sum() print 'Elastic constants / GPa' print (params.C/GPa).round(2) crack = crack.CubicCrystalCrack(C11=None, C12=None, C44=None, crack_surface=params.crack_surface, crack_front=params.crack_front, C=params.C) k1g = crack.k1g(params.surface_energy) print 'k1g', k1g # Crack tip position. tip_x = cryst.cell.diagonal()[0]/2 tip_y = cryst.cell.diagonal()[1]/2 k1 = 1.0 # Apply initial strain field. c = cryst.copy() ux, uy = crack.displacements(cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, k1*k1g) c.positions[:,0] += ux c.positions[:,1] += uy # Center notched configuration in simulation cell and ensure enough vacuum. oldr = a[0].position.copy() c.center(vacuum=params.vacuum, axis=0) c.center(vacuum=params.vacuum, axis=1) tip_x += c[0].position[0] - oldr[0] tip_y += c[0].position[1] - oldr[1] cryst.set_cell(c.cell) cryst.translate(c[0].position - oldr) write('cryst.xyz', cryst, format='extxyz') write('crack.xyz', c, format='extxyz')
2,313
28.666667
75
py
matscipy
matscipy-master/scripts/fracture_mechanics/run_crack_thin_strip.py
# # Copyright 2016 Punit Patel (Warwick U.) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== """ Script to run classical molecular dynamics for a crack slab, incrementing the load in small steps until fracture starts. James Kermode <[email protected]> August 2013 """ import numpy as np import ase.io import ase.units as units from ase.constraints import FixAtoms from ase.md.verlet import VelocityVerlet from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase.io.netcdftrajectory import NetCDFTrajectory from matscipy.fracture_mechanics.crack import (get_strain, get_energy_release_rate, ConstantStrainRate, find_tip_stress_field) import sys sys.path.insert(0, '.') import params # ********** Read input file ************ print 'Loading atoms from file "crack.xyz"' atoms = ase.io.read('crack.xyz') orig_height = atoms.info['OrigHeight'] orig_crack_pos = atoms.info['CrackPos'].copy() # ***** Setup constraints ******* top = atoms.positions[:, 1].max() bottom = atoms.positions[:, 1].min() left = atoms.positions[:, 0].min() right = atoms.positions[:, 0].max() # fix atoms in the top and bottom rows fixed_mask = ((abs(atoms.positions[:, 1] - top) < 1.0) | (abs(atoms.positions[:, 1] - bottom) < 1.0)) fix_atoms = FixAtoms(mask=fixed_mask) print('Fixed %d atoms\n' % fixed_mask.sum()) # Increase epsilon_yy applied to all atoms at constant strain rate strain_atoms = ConstantStrainRate(orig_height, params.strain_rate*params.timestep) atoms.set_constraint(fix_atoms) atoms.set_calculator(params.calc) # ********* Setup and run MD *********** # Set the initial temperature to 2*simT: it will then equilibriate to # simT, by the virial theorem MaxwellBoltzmannDistribution(atoms, 2.0*params.sim_T) # Initialise the dynamical system dynamics = VelocityVerlet(atoms, params.timestep) # Print some information every time step def printstatus(): if dynamics.nsteps == 1: print """ State Time/fs Temp/K Strain G/(J/m^2) CrackPos/A D(CrackPos)/A ---------------------------------------------------------------------------------""" log_format = ('%(label)-4s%(time)12.1f%(temperature)12.6f'+ '%(strain)12.5f%(G)12.4f%(crack_pos_x)12.2f (%(d_crack_pos_x)+5.2f)') atoms.info['label'] = 'D' # Label for the status line atoms.info['time'] = dynamics.get_time()/units.fs atoms.info['temperature'] = (atoms.get_kinetic_energy() / (1.5*units.kB*len(atoms))) atoms.info['strain'] = get_strain(atoms) atoms.info['G'] = get_energy_release_rate(atoms)/(units.J/units.m**2) crack_pos = find_tip_stress_field(atoms) atoms.info['crack_pos_x'] = crack_pos[0] atoms.info['d_crack_pos_x'] = crack_pos[0] - orig_crack_pos[0] print log_format % atoms.info dynamics.attach(printstatus) # Check if the crack has advanced enough and apply strain if it has not def check_if_crack_advanced(atoms): crack_pos = find_tip_stress_field(atoms) # strain if crack has not advanced more than tip_move_tol if crack_pos[0] - orig_crack_pos[0] < params.tip_move_tol: strain_atoms.apply_strain(atoms) dynamics.attach(check_if_crack_advanced, 1, atoms) # Save frames to the trajectory every `traj_interval` time steps trajectory = NetCDFTrajectory(params.traj_file, mode='w') def write_frame(atoms): trajectory.write(atoms) dynamics.attach(write_frame, params.traj_interval, atoms) # Start running! dynamics.run(params.nsteps)
5,425
34.464052
90
py
matscipy
matscipy-master/scripts/fracture_mechanics/neb_crack_tip.py
# # Copyright 2016, 2021 Lars Pastewka (U. Freiburg) # 2016 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== # USAGE: # # Code imports the file 'params.py' from current working directory. params.py # contains simulation parameters. Some parameters can be omitted, see below. import os import sys import numpy as np import ase import ase.constraints import ase.io #import ase.optimize.precon from ase.neb import NEB from ase.data import atomic_numbers from ase.units import GPa import matscipy.fracture_mechanics.crack as crack from matscipy import parameter from matscipy.logger import screen from matscipy.io import savetbl from setup_crack import setup_crack from scipy.integrate import cumtrapz ### import sys sys.path += ['.', '..'] import params ### Optimizer = ase.optimize.FIRE #Optimizer = ase.optimize.precon.LBFGS # Atom types used for outputting the crack tip position. ACTUAL_CRACK_TIP = 'Au' FITTED_CRACK_TIP = 'Ag' ### logger = screen ### # Get general parameters residual_func = parameter('residual_func', crack.displacement_residual) _residual_func = residual_func basename = parameter('basename', 'neb') calc = parameter('calc') fmax_neb = parameter('fmax_neb', 0.1) maxsteps_neb = parameter('maxsteps_neb', 100) Nimages = parameter('Nimages', 7) k_neb = parameter('k_neb', 1.0) a, cryst, crk, k1g, tip_x, tip_y, bond1, bond2, boundary_mask, \ boundary_mask_bulk, tip_mask = setup_crack(logger=logger) # Deformation gradient residual needs full Atoms object and therefore # special treatment here. if _residual_func == crack.deformation_gradient_residual: residual_func = lambda r0, crack, x, y, ref_x, ref_y, k, mask=None:\ _residual_func(r0, crack, x, y, a, ref_x, ref_y, cryst, k, params.cutoff, mask) # Groups g = a.get_array('groups') dirname = os.path.basename(os.getcwd()) initial = ase.io.read('../../initial_state/{0}/initial_state.xyz'.format(dirname)) final_pos = ase.io.read('../../final_state/{0}/final_state.xyz'.format(dirname)) final = initial.copy() final.set_positions(final_pos.positions) # remove marker atoms mask = np.logical_and(initial.numbers != atomic_numbers[ACTUAL_CRACK_TIP], initial.numbers != atomic_numbers[FITTED_CRACK_TIP]) initial = initial[mask] final = final[mask] images = [initial] + [initial.copy() for i in range(Nimages-2)] + [final] neb = NEB(images) neb.interpolate() fit_x, fit_y, _ = initial.info['fitted_crack_tip'] initial_tip_x = [] initial_tip_y = [] for image in neb.images: image.set_calculator(calc) image.set_constraint(ase.constraints.FixAtoms(mask=boundary_mask)) # Fit crack tip (again), and get residuals. fit_x, fit_y, residuals = \ crk.crack_tip_position(image.positions[:len(cryst),0], image.positions[:len(cryst),1], cryst.positions[:,0], cryst.positions[:,1], fit_x, fit_y, params.k1*k1g, mask=tip_mask[:len(cryst)], residual_func=residual_func, return_residuals=True) initial_tip_x += [fit_x] initial_tip_y += [fit_y] logger.pr('Fitted crack tip at %.3f %.3f' % (fit_x, fit_y)) nebfile = open('neb-initial.xyz', 'w') for image in neb.images: ase.io.write(nebfile, image, format='extxyz') nebfile.close() opt = Optimizer(neb) opt.run(fmax_neb, maxsteps_neb) nebfile = open('neb-final.xyz', 'w') for image in neb.images: ase.io.write(nebfile, image, format='extxyz') nebfile.close() fit_x, fit_y, _ = initial.info['fitted_crack_tip'] last_a = None tip_x = [] tip_y = [] work = [] epot_cluster = [] bond_force = [] bond_length = [] for image in neb.images: # Bond length. dr = image[bond1].position - image[bond2].position bond_length += [ np.linalg.norm(dr) ] #assert abs(bond_length[-1]-image.info['bond_length']) < 1e-6 # Get stored potential energy. epot_cluster += [ image.get_potential_energy() ] forces = image.get_forces(apply_constraint=False) df = forces[bond1, :] - forces[bond2, :] bond_force += [ 0.5 * np.dot(df, dr)/np.sqrt(np.dot(dr, dr)) ] # Fit crack tip (again), and get residuals. fit_x, fit_y, residuals = \ crk.crack_tip_position(image.positions[:len(cryst),0], image.positions[:len(cryst),1], cryst.positions[:,0], cryst.positions[:,1], fit_x, fit_y, params.k1*k1g, mask=tip_mask[:len(cryst)], residual_func=residual_func, return_residuals=True) logger.pr('Fitted crack tip at %.3f %.3f' % (fit_x, fit_y)) tip_x += [fit_x] tip_y += [fit_y] # Work due to moving boundary. if last_a is None: work += [ 0.0 ] else: last_forces = last_a.get_forces(apply_constraint=False) # This is the trapezoidal rule. work += [ np.sum(0.5 * (forces[g==0,:]+last_forces[g==0,:]) * (image.positions[g==0,:]-last_a.positions[g==0,:]) ) ] last_a = image last_tip_x = fit_x last_tip_y = fit_y epot_cluster = np.array(epot_cluster)-epot_cluster[0] print('epot_cluster', epot_cluster) work = np.cumsum(work) print('work =', work) tip_x = np.array(tip_x) tip_y = np.array(tip_y) # Integrate bond force potential energy epot = -cumtrapz(bond_force, bond_length, initial=0.0) print('epot =', epot) print('epot_cluster + work', epot_cluster + work) savetbl('{}_eval.out'.format(basename), bond_length=bond_length, bond_force=bond_force, epot=epot, epot_cluster=epot_cluster, work=work, tip_x=tip_x, tip_y=tip_y, initial_tip_x=initial_tip_x, initial_tip_y=initial_tip_y)
7,694
30.280488
82
py
matscipy
matscipy-master/scripts/fracture_mechanics/run_ideal_brittle_solid.py
# # Copyright 2014, 2018 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import sys import numpy as np from scipy.interpolate import interp1d import ase.io from ase.io.netcdftrajectory import NetCDFTrajectory from ase.atoms import Atoms from ase.md import VelocityVerlet from ase.optimize.fire import FIRE from matscipy.fracture_mechanics.idealbrittlesolid import (IdealBrittleSolid, triangular_lattice_slab, find_crack_tip, set_initial_velocities, set_constraints, extend_strip) from matscipy.fracture_mechanics.crack import (thin_strip_displacement_y, ConstantStrainRate) from matscipy.numerical import numerical_forces sys.path.insert(0, '.') import params calc = IdealBrittleSolid(rc=params.rc, k=params.k, a=params.a, beta=params.beta) x_dimer = np.linspace(params.a-(params.rc-params.a), params.a+1.1*(params.rc-params.a),51) dimers = [Atoms('Si2', [(0, 0, 0), (x, 0, 0)], cell=[10., 10., 10.], pbc=True) for x in x_dimer] calc.set_reference_crystal(dimers[0]) e_dimer = [] f_dimer = [] f_num = [] for d in dimers: d.set_calculator(calc) e_dimer.append(d.get_potential_energy()) f_dimer.append(d.get_forces()) f_num.append(numerical_forces(d)) e_dimer = np.array(e_dimer) f_dimer = np.array(f_dimer) f_num = np.array(f_num) assert abs(f_dimer - f_num).max() < 0.1 crystal = triangular_lattice_slab(params.a, 3*params.N, params.N) calc.set_reference_crystal(crystal) crystal.set_calculator(calc) e0 = crystal.get_potential_energy() l = crystal.cell[0,0] h = crystal.cell[1,1] print 'l=', l, 'h=', h # compute surface (Griffith) energy b = crystal.copy() b.set_calculator(calc) shift = calc.parameters['rc']*2 y = crystal.positions[:, 1] b.positions[y > h/2, 1] += shift b.cell[1, 1] += shift e1 = b.get_potential_energy() E_G = (e1 - e0)/l print 'Griffith energy', E_G # compute Griffith strain eps = 0.0 # initial strain is zero eps_max = 2/np.sqrt(3)*(params.rc-params.a)*np.sqrt(params.N-1)/h # Griffith strain assuming harmonic energy deps = eps_max/100. # strain increment e_over_l = 0.0 # initial energy per unit length is zero energy = [] strain = [] while e_over_l < E_G: c = crystal.copy() c.set_calculator(calc) c.positions[:, 1] *= (1.0 + eps) c.cell[1,1] *= (1.0 + eps) e_over_l = c.get_potential_energy()/l energy.append(e_over_l) strain.append(eps) eps += deps energy = np.array(energy) eps_of_e = interp1d(energy, strain, kind='linear') eps_G = eps_of_e(E_G) print 'Griffith strain', eps_G c = crystal.copy() c.info['E_G'] = E_G c.info['eps_G'] = eps_G # open up the cell along x and y by introducing some vaccum orig_cell_width = c.cell[0, 0] orig_cell_height = c.cell[1, 1] c.center(params.vacuum, axis=0) c.center(params.vacuum, axis=1) # centre the slab on the origin c.positions[:, 0] -= c.positions[:, 0].mean() c.positions[:, 1] -= c.positions[:, 1].mean() c.info['cell_origin'] = [-c.cell[0,0]/2, -c.cell[1,1]/2, 0.0] ase.io.write('crack_1.xyz', c, format='extxyz') width = (c.positions[:, 0].max() - c.positions[:, 0].min()) height = (c.positions[:, 1].max() - c.positions[:, 1].min()) c.info['OrigHeight'] = height print(('Made slab with %d atoms, original width and height: %.1f x %.1f A^2' % (len(c), width, height))) top = c.positions[:, 1].max() bottom = c.positions[:, 1].min() left = c.positions[:, 0].min() right = c.positions[:, 0].max() crack_seed_length = 0.3*width strain_ramp_length = 5.0*params.a delta_strain = params.strain_rate*params.dt # fix top and bottom rows, and setup Stokes damping mask # initial use constant strain set_constraints(c, params.a) # apply initial displacment field c.positions[:, 1] += thin_strip_displacement_y( c.positions[:, 0], c.positions[:, 1], params.delta*eps_G, left + crack_seed_length, left + crack_seed_length + strain_ramp_length) print('Applied initial load: delta=%.2f strain=%.4f' % (params.delta, params.delta*eps_G)) ase.io.write('crack_2.xyz', c, format='extxyz') c.set_calculator(calc) # relax initial structure #opt = FIRE(c) #opt.run(fmax=1e-3) ase.io.write('crack_3.xyz', c, format='extxyz') dyn = VelocityVerlet(c, params.dt, logfile=None) set_initial_velocities(dyn.atoms) crack_pos = [] traj = NetCDFTrajectory('traj.nc', 'w', c) dyn.attach(traj.write, 10, dyn.atoms, arrays=['stokes', 'momenta']) dyn.attach(find_crack_tip, 10, dyn.atoms, dt=params.dt*10, store=True, results=crack_pos) # run for 2000 time steps to reach steady state at initial load for i in range(20): dyn.run(100) if extend_strip(dyn.atoms, params.a, params.N, params.M, params.vacuum): set_constraints(dyn.atoms, params.a) # start decreasing strain #set_constraints(dyn.atoms, params.a, delta_strain=delta_strain) strain_atoms = ConstantStrainRate(dyn.atoms.info['OrigHeight'], delta_strain) dyn.attach(strain_atoms.apply_strain, 1, dyn.atoms) for i in range(1000): dyn.run(100) if extend_strip(dyn.atoms, params.a, params.N, params.M, params.vacuum): set_constraints(dyn.atoms, params.a) traj.close() time = 10.0*dyn.dt*np.arange(dyn.get_number_of_steps()/10) np.savetxt('crackpos.dat', np.c_[time, crack_pos])
6,486
31.113861
108
py
matscipy
matscipy-master/scripts/fracture_mechanics/eval_energy_barrier.py
# # Copyright 2014-2016, 2021 Lars Pastewka (U. Freiburg) # 2014-2017 James Kermode (Warwick U.) # 2017 Punit Patel (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import glob import sys import numpy as np from scipy.integrate import cumtrapz import ase.io import ase.units as units from ase.data import atomic_numbers from matscipy.atomic_strain import atomic_strain from matscipy.elasticity import invariants, full_3x3_to_Voigt_6_strain, \ cubic_to_Voigt_6x6, Voigt_6_to_full_3x3_stress, Voigt_6_to_full_3x3_strain,\ rotate_cubic_elastic_constants from matscipy.fracture_mechanics.energy_release import J_integral from matscipy.io import savetbl #from atomistica.analysis import voropp ### sys.path += ['.', '..'] import params ### J_m2 = units.kJ/1000 / 1e20 ### # Atom types used for outputting the crack tip position. ACTUAL_CRACK_TIP = 'Au' FITTED_CRACK_TIP = 'Ag' ### compute_J_integral = len(sys.argv) == 3 and sys.argv[2] == '-J' # Elastic constants #C6 = cubic_to_Voigt_6x6(params.C11, params.C12, params.C44) * units.GPa crack_surface = params.crack_surface crack_front = params.crack_front third_dir = np.cross(crack_surface, crack_front) third_dir = np.array(third_dir) / np.sqrt(np.dot(third_dir, third_dir)) crack_surface = np.array(crack_surface) / \ np.sqrt(np.dot(crack_surface, crack_surface)) crack_front = np.array(crack_front) / \ np.sqrt(np.dot(crack_front, crack_front)) A = np.array([third_dir, crack_surface, crack_front]) if np.linalg.det(A) < 0: third_dir = -third_dir A = np.array([third_dir, crack_surface, crack_front]) #C6 = rotate_cubic_elastic_constants(params.C11, params.C12, params.C44, A) * units.GPa ### #ref = ase.io.read('cluster.xyz') ref = params.cryst.copy() ref_sx, ref_sy, ref_sz = ref.cell.diagonal() ref.set_pbc(True) if compute_J_integral: ref.set_calculator(params.calc) epotref_per_at = ref.get_potential_energies() ### try: prefix = sys.argv[1] except: prefix = 'energy_barrier' fns = sorted(glob.glob('%s_????.xyz' % prefix)) if len(fns) == 0: raise RuntimeError("Could not find files with prefix '{}'.".format(prefix)) tip_x = [] tip_y = [] epot_cluster = [] bond_length = [] bond_force = [] work = [] J_int = [] last_a = None for fn in fns: a = ase.io.read(fn) print(fn, a.arrays.keys()) _tip_x, _tip_y, _tip_z = a.info['fitted_crack_tip'] tip_x += [ _tip_x ] tip_y += [ _tip_y ] # Bond length. bond1 = a.info['bond1'] bond2 = a.info['bond2'] dr = a[bond1].position - a[bond2].position bond_length += [ np.linalg.norm(dr) ] assert abs(bond_length[-1]-a.info['bond_length']) < 1e-6 # Groups g = a.get_array('groups') # Get stored potential energy. epot_cluster += [ a.get_potential_energy() ] # Stored Forces on bond. #a.set_calculator(params.calc) forces = a.get_forces() df = forces[bond1, :] - forces[bond2, :] bond_force += [ 0.5 * np.dot(df, dr)/np.sqrt(np.dot(dr, dr)) ] #bond_force = a.info['force'] #print bond_force[-1], a.info['force'] assert abs(bond_force[-1]-a.info['force']) < 1e-2 # Work due to moving boundary. if last_a is None: work += [ 0.0 ] else: #last_forces = last_a.get_array('forces') last_forces = last_a.get_forces() #(apply_constraint=True) # This is the trapezoidal rule. #print('MAX force', np.abs(forces[g==0,:]).max()) #print('MAX last force', np.abs(last_forces[g==0,:]).max()) #print('MAX d force', np.abs(forces[g==0,:] + last_forces[g==0,:]).max()) work += [ np.sum(0.5 * (forces[g==0,:]+last_forces[g==0,:]) * (a.positions[g==0,:]-last_a.positions[g==0,:]) ) ] # J-integral b = a.copy() mask = np.logical_or(b.numbers == atomic_numbers[ACTUAL_CRACK_TIP], b.numbers == atomic_numbers[FITTED_CRACK_TIP]) del b[mask] G = 0.0 if compute_J_integral: b.set_calculator(params.calc) epot_per_at = b.get_potential_energies() assert abs(epot_cluster[-1]-b.get_potential_energy()) < 1e-6 assert np.all(np.abs(forces[np.logical_not(mask)]-b.get_forces()) < 1e-6) #virial = params.calc.wpot_per_at deformation_gradient, residual = atomic_strain(b, ref, cutoff=2.85) virial = b.get_stresses() strain = full_3x3_to_Voigt_6_strain(deformation_gradient) #virial2 = strain.dot(C6)*vol0 #vols = voropp(b) #virial3 = strain.dot(C6)*vols.reshape(-1,1) #print virial[175] #print virial2[175] #print virial3[175] virial = Voigt_6_to_full_3x3_stress(virial) #vol, dev, J3 = invariants(strain) #b.set_array('vol', vol) #b.set_array('dev', dev) x, y, z = b.positions.T r = np.sqrt((x-_tip_x)**2 + (y-_tip_y)**2) #b.set_array('J_eval', np.logical_and(r > params.eval_r1, # r < params.eval_r2)) #epot = b.get_potential_energies() G = J_integral(b, deformation_gradient, virial, epot_per_at, epotref_per_at, _tip_x, _tip_y, (ref_sx+ref_sy)/8, 3*(ref_sx+ref_sy)/8) J_int += [ G ] #b.set_array('J_integral', np.logical_and(r > params.eval_r1, # r < params.eval_r2)) #ase.io.write('eval_'+fn, b, format='extxyz') last_a = a epot_cluster = np.array(epot_cluster)-epot_cluster[0] work = np.cumsum(work) tip_x = np.array(tip_x) tip_y = np.array(tip_y) bond_length = np.array(bond_length) print 'tip_x =', tip_x # Integrate true potential energy. epot = -cumtrapz(bond_force, bond_length, initial=0.0) print 'epot =', epot print 'epot_cluster + work - epot', epot_cluster + work - epot savetbl('{}_eval.out'.format(prefix), bond_length=bond_length, bond_force=bond_force, epot=epot, epot_cluster=epot_cluster, work=work, tip_x=tip_x, tip_y=tip_y, J_int=J_int) # Fit and subtract first energy minimum i = 1 while epot[i] < epot[i-1]: i += 1 print 'i =', i c, b, a = np.polyfit(bond_length[i-2:i+2]-bond_length[i-1], epot[i-2:i+2], 2) print 'a, b, c =', a, b, c min_bond_length = -b/(2*c) print 'min_bond_length =', min_bond_length+bond_length[i-1], ', delta(min_bond_length) =', min_bond_length min_epot = a+b*min_bond_length+c*min_bond_length**2 print 'min_epot =', min_epot, ', epot[i-1] =', epot[i-1] c, b, a = np.polyfit(bond_length[i-2:i+2]-bond_length[i-1], tip_x[i-2:i+2], 2) min_tip_x = a+b*min_bond_length+c*min_bond_length**2 c, b, a = np.polyfit(bond_length[i-2:i+2]-bond_length[i-1], tip_y[i-2:i+2], 2) min_tip_y = a+b*min_bond_length+c*min_bond_length**2 min_bond_length += bond_length[i-1] epot -= min_epot tip_x = tip_x-min_tip_x tip_y = tip_y-min_tip_y savetbl('{}_eval.out'.format(prefix), bond_length=bond_length, bond_force=bond_force, epot=epot, epot_cluster=epot_cluster, work=work, tip_x=tip_x, tip_y=tip_y, J_int=J_int) # Fit and subtract second energy minimum i = len(epot)-1 while epot[i] > epot[i-1]: i -= 1 print 'i =', i c, b, a = np.polyfit(bond_length[i-2:i+3]-bond_length[i], epot[i-2:i+3], 2) min_bond_length2 = -b/(2*c) print 'min_bond_length2 =', min_bond_length2+bond_length[i], ', delta(min_bond_length2) =', min_bond_length2 min_epot2 = a+b*min_bond_length2+c*min_bond_length2**2 print 'min_epot2 =', min_epot2, ', epot[i] =', epot[i] min_bond_length2 += bond_length[i] corrected_epot = epot - min_epot2*(bond_length-min_bond_length)/(min_bond_length2-min_bond_length) savetbl('{}_eval.out'.format(prefix), bond_length=bond_length, bond_force=bond_force, epot=epot, corrected_epot=corrected_epot, epot_cluster=epot_cluster, work=work, tip_x=tip_x, tip_y=tip_y, J_int=J_int)
9,715
30.751634
108
py
matscipy
matscipy-master/scripts/fracture_mechanics/plot_two_bonds.py
# # Copyright 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import numpy as np import matplotlib.pyplot as plt import ase.units import ase.io from scipy.signal import argrelextrema from scipy.interpolate import splrep, splev J_per_m2 = ase.units.J/ase.units.m**2 bond_lengths1, bond1_forces1, epot1, epot_cluster1, work1, tip_x1, tip_z1 = \ np.loadtxt('bond_1_eval.out', unpack=True) bond_lengths2, bond2_forces2, epot2, epot_cluster2, work2, tip_x2, tip_z2 = \ np.loadtxt('bond_2_eval.out', unpack=True) minima1 = argrelextrema(epot1, np.less) minima2 = argrelextrema(epot2, np.less) maxima1 = argrelextrema(epot1, np.greater) maxima2 = argrelextrema(epot2, np.greater) Ea_1 = epot1[maxima1][0] - epot1[minima1][0] dE_1 = epot1[minima1][1] - epot1[minima1][0] print 'Ea_1 = %.3f eV' % Ea_1 print 'dE_1 = %.3f eV' % dE_1 print Ea_2 = epot2[maxima2][0] - epot2[minima2][0] dE_2 = epot2[minima2][1] - epot2[minima2][0] print 'Ea_2 = %.3f eV' % Ea_2 print 'dE_2 = %.3f eV' % dE_2 print E0_1 = epot1[minima1][0] E0_2 = epot2[minima2][0] E0_12 = epot1[minima1][-1] - epot2[minima1][0] plt.figure(1) plt.clf() plt.plot(tip_x1, epot1 - E0_1, 'b.-', label='Bond 1') plt.plot(tip_x2, epot2 - E0_1 + E0_12, 'c.-', label='Bond 2') plt.plot(tip_x2 - tip_x2[minima2][0] + tip_x1[minima1][0], epot2 - E0_2, 'c.--', label='Bond 2, shifted') plt.plot(tip_x1[minima1], epot1[minima1] - E0_1, 'ro', mec='r', label='Bond 1 minima') plt.plot(tip_x2[minima2], epot2[minima1] - E0_1 + E0_12, 'mo', mec='m', label='Bond 2 minima') plt.plot(tip_x2[minima2]-tip_x2[minima2][0] + tip_x1[minima1][0], epot2[minima1] - E0_1, 'mo', mec='m', mfc='w', label='Bond 2 minima, shifted') plt.plot(tip_x1[maxima1], epot1[maxima1] - E0_1, 'rd', mec='r', label='Bond 1 TS') plt.plot(tip_x2[maxima2], epot2[maxima1] - E0_1 + E0_12, 'md', mec='m', label='Bond 2 TS') plt.plot(tip_x2[maxima2] - tip_x2[minima2][0] + tip_x1[minima1][0], epot2[maxima1] - E0_1, 'md', mec='m', mfc='w', label='Bond 2 TS, shifted') plt.xlabel(r'Crack position / $\mathrm{\AA}$') plt.ylabel(r'Potential energy / eV') plt.legend(loc='upper right') #plt.ylim(-0.05, 0.30) plt.draw() plt.figure(2) #plt.clf() bond_length, gamma = np.loadtxt('../cohesive-stress/gamma_bond_length.out', unpack=True) s = bond_length - bond_length[0] s1 = bond_lengths1 - bond_length[0] surface = ase.io.read('../cohesive-stress/surface.xyz') area = surface.cell[0,0]*surface.cell[2,2] gamma_sp = splrep(bond_length, gamma) E_surf = splev(bond_lengths1, gamma_sp)*area plt.plot(s1, (epot1 - E0_1), '-', label='total energy') plt.plot(s, E_surf, '-', label=r'surface energy') plt.plot(s1, (epot1 - E0_1 - E_surf), '--', label='elastic energy') #plt.xlim(2.35, 4.5) plt.axhline(0, color='k') plt.xlabel(r'Bond extension $s$ / $\mathrm{\AA}$') plt.ylabel(r'Energy / eV/cell') plt.legend(loc='upper right') plt.draw()
4,640
33.634328
90
py
matscipy
matscipy-master/scripts/fracture_mechanics/quasistatic_crack.py
# # Copyright 2014-2015, 2021 Lars Pastewka (U. Freiburg) # 2015 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== # USAGE: # # Code imports the file 'params.py' from current working directory. params.py # contains simulation parameters. Some parameters can be omitted, see below. # # Parameters # ---------- # calc : ase.Calculator # Calculator object for energy and force computation. # tip_x0 : float # Initial x-position of crack tip. # tip_y0 : float # Initial y-position of crack tip. # tip_dx : array-like # Displacement of tip in x-direction during run. x- and y-positions will be # optimized self-consistently if omitted. # tip_dy : array-like # Displacement of tip in y-direction during run. Position will be optimized # self-consistently if omitted. import os import sys import numpy as np import ase import ase.io import ase.constraints import ase.optimize from ase.units import GPa import matscipy.fracture_mechanics.crack as crack from matscipy import parameter from matscipy.logger import screen from setup_crack import setup_crack ### sys.path += ['.', '..'] import params ### # Atom types used for outputting the crack tip position. ACTUAL_CRACK_TIP = 'Au' FITTED_CRACK_TIP = 'Ag' ### logger = screen ### a, cryst, crk, k1g, tip_x0, tip_y0, bond1, bond2, boundary_mask, \ boundary_mask_bulk, tip_mask = setup_crack(logger=logger) ase.io.write('notch.xyz', a, format='extxyz') # Global parameters basename = parameter('basename', 'quasistatic_crack') calc = parameter('calc') fmax = parameter('fmax', 0.01) # Determine simulation control k1_list = parameter('k1') old_k1 = k1_list[0] nsteps = len(k1_list) tip_dx_list = parameter('tip_dx', np.zeros(nsteps)) tip_dy_list = parameter('tip_dy', np.zeros(nsteps)) # Run crack calculation. tip_x = tip_x0 tip_y = tip_y0 a.set_calculator(calc) for i, ( k1, tip_dx, tip_dy ) in enumerate(zip(k1_list, tip_dx_list, tip_dy_list)): logger.pr('=== k1 = {0}*k1g, tip_dx = {1}, tip_dy = {2} ===' \ .format(k1, tip_dx, tip_dy)) if tip_dx is None or tip_dy is None: # # Optimize crack tip position # old_y = tip_y+1.0 old_x = tip_x+1.0 while abs(tip_x-old_x) > 1e-6 and abs(tip_y-old_y) > 1e-6: b = cryst.copy() ux, uy = crk.displacements(cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, k*k1g) b.positions[:,0] += ux b.positions[:,1] += uy a.set_constraint(None) a.positions[boundary_mask] = b.positions[boundary_mask] a.set_constraint(ase.constraints.FixAtoms(mask=boundary_mask)) logger.pr('Optimizing positions...') opt = ase.optimize.FIRE(a, logfile=None) opt.run(fmax=fmax) logger.pr('...done. Converged within {0} steps.' \ .format(opt.get_number_of_steps())) old_x = tip_x old_y = tip_y tip_x, tip_y = crk.crack_tip_position(a.positions[:,0], a.positions[:,1], cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, k*k1g, mask=mask) else: # # Do not optimize tip position. # tip_x = tip_x0+tip_dx tip_y = tip_y0+tip_dy logger.pr('Setting crack tip position to {0} {1}' \ .format(tip_x, tip_y)) # Scale strain field and optimize crack a.set_constraint(None) x, y = crk.scale_displacements(a.positions[:len(cryst),0], a.positions[:len(cryst),1], cryst.positions[:,0], cryst.positions[:,1], old_k1, k1) a.positions[:len(cryst),0] = x a.positions[:len(cryst),1] = y # Optimize atoms in center a.set_constraint(ase.constraints.FixAtoms(mask=boundary_mask)) logger.pr('Optimizing positions...') opt = ase.optimize.FIRE(a) opt.run(fmax=fmax) logger.pr('...done. Converged within {0} steps.' \ .format(opt.get_number_of_steps())) old_k1 = k1 # Output optimized configuration ot file. Include the mask array in # output, so we know which atoms were used in fitting. a.set_array('atoms_used_for_fitting_crack_tip', tip_mask) # Output a file that contains the target crack tip (used for # the displacmenets of the boundary atoms) and the fitted crack tip # positions. The target crack tip is marked by a Hydrogen atom. b = a.copy() b += ase.Atom(ACTUAL_CRACK_TIP, (tip_x, tip_y, b.cell[2, 2]/2)) # Measure the true (fitted) crack tip position. try: measured_tip_x, measured_tip_y = \ crk.crack_tip_position(a.positions[:,0], a.positions[:,1], cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, k1*k1g, mask=tip_mask) measured_tip_x %= a.cell[0][0] measured_tip_y %= a.cell[0][0] except: measured_tip_x = 0.0 measured_tip_y = 0.0 # The fitted crack tip is marked by a Helium atom. b += ase.Atom(FITTED_CRACK_TIP, (measured_tip_x, measured_tip_y, b.cell[2, 2]/2)) b.info['bond_length'] = a.get_distance(bond1, bond2) b.info['energy'] = a.get_potential_energy() b.info['cell_origin'] = [0, 0, 0] ase.io.write('%s_%4.4i.xyz' % (basename, i), b, format='extxyz')
7,575
35.956098
82
py
matscipy
matscipy-master/scripts/fracture_mechanics/setup_crack.py
# # Copyright 2015, 2021 Lars Pastewka (U. Freiburg) # 2017 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import numpy as np import ase.optimize from ase.units import GPa import matscipy.fracture_mechanics.crack as crack from matscipy import has_parameter, parameter from matscipy.elasticity import fit_elastic_constants from matscipy.hydrogenate import hydrogenate from matscipy.logger import screen from matscipy.neighbours import neighbour_list ### def setup_crack(logger=screen): calc = parameter('calc') cryst = parameter('cryst').copy() cryst.set_pbc(True) # Double check elastic constants. We're just assuming this is really a periodic # system. (True if it comes out of the cluster routines.) compute_elastic_constants = parameter('compute_elastic_constants', False) elastic_fmax = parameter('elastic_fmax', 0.01) elastic_symmetry = parameter('elastic_symmetry', 'triclinic') elastic_optimizer = parameter('elastic_optimizer', ase.optimize.FIRE) if compute_elastic_constants: cryst.set_calculator(calc) log_file = open('elastic_constants.log', 'w') C, C_err = fit_elastic_constants(cryst, verbose=False, symmetry=elastic_symmetry, optimizer=elastic_optimizer, logfile=log_file, fmax=elastic_fmax) log_file.close() logger.pr('Measured elastic constants (in GPa):') logger.pr(np.round(C*10/GPa)/10) crk = crack.CubicCrystalCrack(parameter('crack_surface'), parameter('crack_front'), Crot=C/GPa) else: if has_parameter('C'): crk = crack.CubicCrystalCrack(parameter('crack_surface'), parameter('crack_front'), C=parameter('C')) else: crk = crack.CubicCrystalCrack(parameter('crack_surface'), parameter('crack_front'), parameter('C11'), parameter('C12'), parameter('C44')) logger.pr('Elastic constants used for boundary condition (in GPa):') logger.pr(np.round(crk.C*10)/10) # Get Griffith's k1. k1g = crk.k1g(parameter('surface_energy')) logger.pr('Griffith k1 = %f' % k1g) # Apply initial strain field. tip_x = parameter('tip_x', cryst.cell.diagonal()[0]/2) tip_y = parameter('tip_y', cryst.cell.diagonal()[1]/2) bondlength = parameter('bondlength', 2.7) bulk_nn = parameter('bulk_nn', 4) a = cryst.copy() a.set_pbc([False, False, True]) hydrogenate_flag = parameter('hydrogenate', False) hydrogenate_crack_face_flag = parameter('hydrogenate_crack_face', True) if hydrogenate_flag and not hydrogenate_crack_face_flag: # Get surface atoms of cluster with crack a = hydrogenate(cryst, bondlength, parameter('XH_bondlength'), b=a) g = a.get_array('groups') g[a.numbers==1] = -1 a.set_array('groups', g) cryst = a.copy() k1 = parameter('k1') try: k1 = k1[0] except: pass ux, uy = crk.displacements(cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, k1*k1g) a.positions[:len(cryst),0] += ux a.positions[:len(cryst),1] += uy # Center notched configuration in simulation cell and ensure enough vacuum. oldr = a[0].position.copy() vacuum = parameter('vacuum') a.center(vacuum=vacuum, axis=0) a.center(vacuum=vacuum, axis=1) tip_x += a[0].x - oldr[0] tip_y += a[0].y - oldr[1] # Choose which bond to break. bond1, bond2 = \ parameter('bond', crack.find_tip_coordination(a, bondlength=bondlength, bulk_nn=bulk_nn)) if parameter('center_crack_tip_on_bond', False): tip_x, tip_y, dummy = (a.positions[bond1]+a.positions[bond2])/2 # Hydrogenate? coord = np.bincount(neighbour_list('i', a, bondlength), minlength=len(a)) a.set_array('coord', coord) if parameter('optimize_full_crack_face', False): g = a.get_array('groups') gcryst = cryst.get_array('groups') coord = a.get_array('coord') g[coord!=4] = -1 gcryst[coord!=4] = -1 a.set_array('groups', g) cryst.set_array('groups', gcryst) if hydrogenate_flag and hydrogenate_crack_face_flag: # Get surface atoms of cluster with crack exclude = np.logical_and(a.get_array('groups')==1, coord!=4) a.set_array('exclude', exclude) a = hydrogenate(cryst, bondlength, parameter('XH_bondlength'), b=a, exclude=exclude) g = a.get_array('groups') g[a.numbers==1] = -1 a.set_array('groups', g) basename = parameter('basename', 'energy_barrier') ase.io.write('{0}_hydrogenated.xyz'.format(basename), a, format='extxyz') # Move reference crystal by same amount cryst.set_cell(a.cell) cryst.set_pbc([False, False, True]) cryst.translate(a[0].position - oldr) # Groups mark the fixed region and the region use for fitting the crack tip. g = a.get_array('groups') gcryst = cryst.get_array('groups') logger.pr('Opening bond {0}--{1}, initial bond length {2}'. format(bond1, bond2, a.get_distance(bond1, bond2, mic=True))) # centre vertically on the opening bond if parameter('center_cell_on_bond', True): a.translate([0., a.cell[1,1]/2.0 - (a.positions[bond1, 1] + a.positions[bond2, 1])/2.0, 0.]) a.info['bond1'] = bond1 a.info['bond2'] = bond2 return a, cryst, crk, k1g, tip_x, tip_y, bond1, bond2, g==0, gcryst==0, g==1
6,642
36.531073
97
py
matscipy
matscipy-master/scripts/fracture_mechanics/eval_J_integral.py
# # Copyright 2014, 2021 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import glob import sys import numpy as np from scipy.integrate import cumtrapz import ase.io import ase.units as units import ase.optimize from ase.data import atomic_numbers from ase.parallel import parprint from matscipy.atomic_strain import atomic_strain from matscipy.neighbours import neighbour_list from matscipy.elasticity import invariants, full_3x3_to_Voigt_6_strain, \ cubic_to_Voigt_6x6, Voigt_6_to_full_3x3_stress, Voigt_6_to_full_3x3_strain,\ rotate_cubic_elastic_constants from matscipy.fracture_mechanics.energy_release import J_integral ### sys.path += [ "." ] import params ### J_m2 = units.kJ/1000 / 1e20 ### # Atom types used for outputting the crack tip position. ACTUAL_CRACK_TIP = 'Au' FITTED_CRACK_TIP = 'Ag' ### # Get cohesive energy a = params.cryst.info['unitcell'].copy() a.set_calculator(params.calc) e0 = a.get_potential_energy()/len(a) print 'cohesive energy = {} eV/atom'.format(e0) # Get surface energy and stress a *= (1,3,1) a.set_pbc([True, False, True]) ase.optimize.FIRE(a, logfile=None).run(fmax=params.fmax) coord = np.bincount(neighbour_list("i", a, 2.85)) esurf0 = (a.get_potential_energy() - e0*len(a)) sx, sy, sz = a.cell.diagonal() print 'surface energy = {} J/m^2'.format(esurf0/(2*sx*sz)/J_m2) esurf0 = a.get_potential_energies() esurf1 = esurf0[1] esurf0 = esurf0[0] print 'cohesive energy (surface atoms) = {}, {} eV/atom'.format(esurf0, esurf1) vsurf0 = a.get_stresses() vsurf1 = Voigt_6_to_full_3x3_stress(vsurf0[1]) vsurf0 = Voigt_6_to_full_3x3_stress(vsurf0[0]) # Reference configuration for strain calculation a = ase.io.read(sys.argv[1]) ref = ase.io.read(sys.argv[2]) ### # Get crack tip position tip_x, tip_y, tip_z = a.info['fitted_crack_tip'] # Set calculator a.set_calculator(params.calc) # Relax positions del a[np.logical_or(a.numbers == atomic_numbers[ACTUAL_CRACK_TIP], a.numbers == atomic_numbers[FITTED_CRACK_TIP])] g = a.get_array('groups') a.set_constraint(ase.constraints.FixAtoms(mask=g==0)) a.set_calculator(params.calc) parprint('Optimizing positions...') opt = ase.optimize.FIRE(a, logfile=None) opt.run(fmax=params.fmax) parprint('...done. Converged within {0} steps.' \ .format(opt.get_number_of_steps())) # Get atomic strain i, j = neighbour_list("ij", a, cutoff=2.85) deformation_gradient, residual = atomic_strain(a, ref, neighbours=(i, j)) # Get atomic stresses virial = a.get_stresses() # Note: get_stresses returns the virial in Atomistica! strain = full_3x3_to_Voigt_6_strain(deformation_gradient) vol_strain, dev_strain, J3_strain = invariants(strain) a.set_array('strain', strain) a.set_array('vol_strain', vol_strain) a.set_array('dev_strain', dev_strain) a.set_array('virial', virial) virial = Voigt_6_to_full_3x3_stress(virial) # Coordination count coord = np.bincount(i) coord_coord = np.bincount(i, weights=coord[j]) mask = coord!=4 mask = np.ones_like(mask) eref = e0*np.ones(len(a)) eref[coord_coord==15] = esurf1 eref[coord!=4] = esurf0 #virial[coord_coord==15] -= vsurf1 #virial[coord!=4] -= vsurf0 a.set_array('coordination', coord) a.set_array('coord_coord', coord_coord) a.set_array('eref', eref) ase.io.write('eval_J_integral.xyz', a, format='extxyz') # Evaluate J-integral epot = a.get_potential_energies() for r1, r2 in zip(params.eval_r1, params.eval_r2): G = J_integral(a, deformation_gradient, virial, epot, eref, tip_x, tip_y, r1, r2, mask) print '[From {0} A to {1} A]: J = {2} J/m^2'.format(r1, r2, G/J_m2)
5,295
30.903614
80
py
matscipy
matscipy-master/scripts/fracture_mechanics/sinclair_plot.py
# # Copyright 2014, 2020 James Kermode (Warwick U.) # 2020 Arnaud Allera (U. Lyon 1) # 2014 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os import sys import itertools import numpy as np import h5py import matplotlib.pyplot as plt import seaborn as sns sns.set_context('talk', font_scale=1.0) import ase.io from ase.units import GPa from matscipy import parameter from matscipy.elasticity import fit_elastic_constants from matscipy.fracture_mechanics.crack import CubicCrystalCrack, SinclairCrack args = sys.argv[1:] if not args: args = ['.'] # current directory only sys.path.insert(0, args[0]) import params calc = parameter('calc') fmax = parameter('fmax', 1e-3) vacuum = parameter('vacuum', 10.0) flexible = parameter('flexible', True) extended_far_field = parameter('extended_far_field', False) k0 = parameter('k0', 1.0) alpha0 = parameter('alpha0', 0.0) # initial guess for crack position colors = parameter('colors', ["#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E"]) colors = itertools.cycle(colors) # compute elastic constants cryst = params.cryst.copy() cryst.pbc = True cryst.calc = calc C, C_err = fit_elastic_constants(cryst, symmetry=parameter('elastic_symmetry', 'triclinic')) crk = CubicCrystalCrack(parameter('crack_surface'), parameter('crack_front'), Crot=C/GPa) # Get Griffith's k1. k1g = crk.k1g(parameter('surface_energy')) print('Griffith k1 = %f' % k1g) cluster = params.cluster.copy() plot_approx = parameter('plot_approx', False) if plot_approx: fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 10)) axs = [ax1, ax2] else: fig, ax1 = plt.subplots(figsize=(6, 6)) ax2 = ax1 axs = [ax1] plot_labels = parameter('plot_labels', []) if plot_labels == []: plot_labels = [ f'$R$ = {directory.split("_")[1]}' for directory in args ] atoms = [] for directory, color, label in zip(args, colors, plot_labels): fn = f'{directory}/x_traj.h5' if os.path.exists(fn): cluster = ase.io.read(f'{directory}/cluster.cfg') sc = SinclairCrack(crk, cluster, calc, k0 * k1g, alpha=alpha0, variable_alpha=flexible, variable_k=True, vacuum=vacuum, extended_far_field=extended_far_field) with h5py.File(fn) as hf: x = hf['x'] sc.set_dofs(x[0]) a = sc.atoms atoms.append(a) k = x[:, -1] if flexible: alpha = x[:, -2] ax1.plot(k / k1g, alpha, c=color, label=label) else: u = x[:, :-1] ax1.plot(k / k1g, np.linalg.norm(u, axis=1), c=color, label=label) if plot_approx and os.path.exists(f'{directory}/traj_approximate.txt'): print(f'Loading {directory}/traj_approximate.txt...') alpha, k = np.loadtxt(f'{directory}/traj_approximate.txt').T ax2.plot(k, alpha, '--', c=color, label=label) for a in atoms[:-1]: a.set_cell(atoms[-1].cell) a.center(axis=0) a.center(axis=1) ase.io.write('atoms.xyz', atoms) klim = parameter('klim', ()) alphalim = parameter('alphalim', ()) for ax in axs: ax.axvline(1.0, color='k') if klim is not (): ax.set_xlim(klim) if alphalim is not (): ax.set_ylim(alphalim) if flexible: ax.set_ylabel(r'Crack position $\alpha$') else: ax.set_ylabel(r'Norm of corrector $\||u\||$ / $\mathrm{\AA{}}$') ax.legend(loc='upper right') ax2.set_xlabel(r'Stress intensity factor $K/K_{G}$') pdffile = parameter('pdffile', 'plot.pdf') plt.savefig(pdffile)
4,477
30.097222
83
py
matscipy
matscipy-master/scripts/fracture_mechanics/optimize_crack_tip.py
# # Copyright 2016, 2021 Lars Pastewka (U. Freiburg) # 2016 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== # USAGE: # # Code imports the file 'params.py' from current working directory. params.py # contains simulation parameters. Some parameters can be omitted, see below. import os import sys import numpy as np import ase import ase.constraints import ase.io import ase.optimize from ase.data import atomic_numbers from ase.units import GPa import matscipy.fracture_mechanics.crack as crack from matscipy import parameter from matscipy.logger import screen from setup_crack import setup_crack ### import sys sys.path += ['.', '..'] import params ### Optimizer = ase.optimize.FIRE # Atom types used for outputting the crack tip position. ACTUAL_CRACK_TIP = 'Au' FITTED_CRACK_TIP = 'Ag' ### logger = screen ### a, cryst, crk, k1g, tip_x, tip_y, bond1, bond2, boundary_mask, \ boundary_mask_bulk, tip_mask = setup_crack(logger=logger) ase.io.write('notch.xyz', a, format='extxyz') # Get general parameters basename = parameter('basename', 'crack_tip') calc = parameter('calc') fmax = parameter('fmax', 0.01) # Get parameter used for fitting crack tip position residual_func = parameter('residual_func', crack.displacement_residual) _residual_func = residual_func tip_tol = parameter('tip_tol', 1e-4) tip_mixing_alpha = parameter('tip_mixing_alpha', 1.0) write_trajectory_during_optimization = parameter('write_trajectory_during_optimization', False) tip_x = (a.positions[bond1, 0] + a.positions[bond2, 0])/2 tip_y = (a.positions[bond1, 1] + a.positions[bond2, 1])/2 logger.pr('Optimizing tip position -> initially centering tip bond. ' 'Tip positions = {} {}'.format(tip_x, tip_y)) # Check if there is a request to restart from a positions file restart_from = parameter('restart_from', 'N/A') if restart_from != 'N/A': logger.pr('Restarting from {0}'.format(restart_from)) a = ase.io.read(restart_from) # remove any marker atoms marker_mask = np.logical_and(a.numbers != atomic_numbers[ACTUAL_CRACK_TIP], a.numbers != atomic_numbers[FITTED_CRACK_TIP]) a = a[marker_mask] tip_x, tip_y = crk.crack_tip_position(a.positions[:len(cryst),0], a.positions[:len(cryst),1], cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g, mask=tip_mask[:len(cryst)], residual_func=residual_func) logger.pr('Optimizing tip position -> initially autodetected tip position. ' 'Tip positions = {} {}'.format(tip_x, tip_y)) else: tip_x = (a.positions[bond1, 0] + a.positions[bond2, 0])/2 tip_y = (a.positions[bond1, 1] + a.positions[bond2, 1])/2 logger.pr('Optimizing tip position -> initially centering tip bond. ' 'Tip positions = {} {}'.format(tip_x, tip_y)) # Assign calculator. a.set_calculator(calc) log_file = open('{0}.log'.format(basename), 'w') if write_trajectory_during_optimization: traj_file = ase.io.NetCDFTrajectory('{0}.nc'.format(basename), mode='w', atoms=a) traj_file.write() else: traj_file = None # Deformation gradient residual needs full Atoms object and therefore # special treatment here. if _residual_func == crack.deformation_gradient_residual: residual_func = lambda r0, crack, x, y, ref_x, ref_y, k, mask=None:\ _residual_func(r0, crack, x, y, a, ref_x, ref_y, cryst, k, params.cutoff, mask) old_x = tip_x old_y = tip_y converged = False while not converged: #b = cryst.copy() u0x, u0y = crk.displacements(cryst.positions[:,0], cryst.positions[:,1], old_x, old_y, params.k1*k1g) ux, uy = crk.displacements(cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g) a.set_constraint(None) # Displace atom positions a.positions[:len(cryst),0] += ux-u0x a.positions[:len(cryst),1] += uy-u0y a.positions[bond1,0] -= ux[bond1]-u0x[bond1] a.positions[bond1,1] -= uy[bond1]-u0y[bond1] a.positions[bond2,0] -= ux[bond2]-u0x[bond2] a.positions[bond2,1] -= uy[bond2]-u0y[bond2] # Set bond length and boundary atoms explicitly to avoid numerical drift a.positions[boundary_mask,0] = \ cryst.positions[boundary_mask_bulk,0] + ux[boundary_mask_bulk] a.positions[boundary_mask,1] = \ cryst.positions[boundary_mask_bulk,1] + uy[boundary_mask_bulk] # Fix outer boundary a.set_constraint(ase.constraints.FixAtoms(mask=boundary_mask)) logger.pr('Optimizing positions...') opt = Optimizer(a, logfile=log_file) if traj_file: opt.attach(traj_file.write) opt.run(fmax=fmax) logger.pr('...done. Converged within {0} steps.' \ .format(opt.get_number_of_steps())) old_x = tip_x old_y = tip_y tip_x, tip_y = crk.crack_tip_position(a.positions[:len(cryst),0], a.positions[:len(cryst),1], cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g, mask=tip_mask[:len(cryst)], residual_func=residual_func) dtip_x = tip_x-old_x dtip_y = tip_y-old_y logger.pr('- Fitted crack tip (before mixing) is at {:3.2f} {:3.2f} ' '(= {:3.2e} {:3.2e} from the former position).'.format(tip_x, tip_y, dtip_x, dtip_y)) tip_x = old_x + tip_mixing_alpha*dtip_x tip_y = old_y + tip_mixing_alpha*dtip_y logger.pr('- New crack tip (after mixing) is at {:3.2f} {:3.2f} ' '(= {:3.2e} {:3.2e} from the former position).'.format(tip_x, tip_y, tip_x-old_x, tip_y-old_y)) converged = np.asscalar(abs(dtip_x) < tip_tol and abs(dtip_y) < tip_tol) # Fit crack tip (again), and get residuals. fit_x, fit_y, residuals = \ crk.crack_tip_position(a.positions[:len(cryst),0], a.positions[:len(cryst),1], cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g, mask=tip_mask[:len(cryst)], residual_func=residual_func, return_residuals=True) logger.pr('Measured crack tip at %f %f' % (fit_x, fit_y)) b = a.copy() # The target crack tip is marked by a gold atom. b += ase.Atom(ACTUAL_CRACK_TIP, (tip_x, tip_y, b.cell.diagonal()[2]/2)) b.info['actual_crack_tip'] = (tip_x, tip_y, b.cell.diagonal()[2]/2) # The fitted crack tip is marked by a silver atom. b += ase.Atom(FITTED_CRACK_TIP, (fit_x, fit_y, b.cell.diagonal()[2]/2)) b.info['fitted_crack_tip'] = (fit_x, fit_y, b.cell.diagonal()[2]/2) b.info['energy'] = a.get_potential_energy() b.info['cell_origin'] = [0, 0, 0] ase.io.write('{0}.xyz'.format(basename), b, format='extxyz') log_file.close() if traj_file: traj_file.close()
9,148
36.962656
108
py
matscipy
matscipy-master/scripts/fracture_mechanics/make_crack_thin_strip.py
# # Copyright 2014, 2020 James Kermode (Warwick U.) # 2016 Punit Patel (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== """ Script to generate a crack slab, and apply initial strain ramp James Kermode <[email protected]> August 2014 """ import numpy as np from ase.lattice.cubic import Diamond from ase.constraints import FixAtoms, StrainFilter from ase.optimize import FIRE import ase.io import ase.units as units from matscipy.elasticity import (measure_triclinic_elastic_constants, rotate_elastic_constants, youngs_modulus, poisson_ratio) from matscipy.fracture_mechanics.crack import (print_crack_system, G_to_strain, thin_strip_displacement_y, find_tip_stress_field) import sys sys.path.insert(0, '.') import params a = params.cryst.copy() # ***** Find eqm. lattice constant ****** # find the equilibrium lattice constant by minimising atoms wrt virial # tensor given by SW pot (possibly replace this with parabola fit in # another script and hardcoded a0 here) a.set_calculator(params.calc) if hasattr(params, 'relax_bulk') and params.relax_bulk: print('Minimising bulk unit cell...') opt = FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0])) opt.run(fmax=params.bulk_fmax) a0 = a.cell[0, 0] print('Lattice constant %.3f A\n' % a0) a.set_calculator(params.calc) # ******* Find elastic constants ******* # Get 6x6 matrix of elastic constants C_ij C = measure_triclinic_elastic_constants(a, optimizer=FIRE, fmax=params.bulk_fmax) print('Elastic constants (GPa):') print((C / units.GPa).round(0)) print('') E = youngs_modulus(C, params.cleavage_plane) print('Young\'s modulus %.1f GPa' % (E / units.GPa)) nu = poisson_ratio(C, params.cleavage_plane, params.crack_direction) print('Poisson ratio % .3f\n' % nu) # **** Setup crack slab unit cell ****** directions = [params.crack_direction, params.cleavage_plane, params.crack_front] print_crack_system(directions) # now, we build system aligned with requested crystallographic orientation unit_slab = Diamond(directions=directions, size=(1, 1, 1), symbol='Si', pbc=True, latticeconstant=a0) if (hasattr(params, 'check_rotated_elastic_constants') and # Check that elastic constants of the rotated system # lead to same Young's modulus and Poisson ratio params.check_rotated_elastic_constants): unit_slab.set_calculator(params.calc) C_r1 = measure_triclinic_elastic_constants(unit_slab, optimizer=FIRE, fmax=params.bulk_fmax) R = np.array([ np.array(x)/np.linalg.norm(x) for x in directions ]) C_r2 = rotate_elastic_constants(C, R) for C_r in [C_r1, C_r2]: S_r = np.linalg.inv(C_r) E_r = 1./S_r[1,1] print('Young\'s modulus from C_r: %.1f GPa' % (E_r / units.GPa)) assert (abs(E_r - E)/units.GPa < 1e-3) nu_r = -S_r[1,2]/S_r[1,1] print('Possion ratio from C_r: %.3f' % (nu_r)) assert (abs(nu_r - nu) < 1e-3) print('Unit slab with %d atoms per unit cell:' % len(unit_slab)) print(unit_slab.cell) print('') # center vertically half way along the vertical bond between atoms 0 and 1 unit_slab.positions[:, 1] += (unit_slab.positions[1, 1] - unit_slab.positions[0, 1]) / 2.0 # map positions back into unit cell unit_slab.set_scaled_positions(unit_slab.get_scaled_positions()) # Make a surface unit cell by repllcating and adding some vaccum along y surface = unit_slab * [1, params.surf_ny, 1] surface.center(params.vacuum, axis=1) # ********** Surface energy ************ # Calculate surface energy per unit area surface.set_calculator(params.calc) if hasattr(params, 'relax_bulk') and params.relax_bulk: print('Minimising surface unit cell...') opt = FIRE(surface) opt.run(fmax=params.bulk_fmax) E_surf = surface.get_potential_energy() E_per_atom_bulk = a.get_potential_energy() / len(a) area = surface.get_volume() / surface.cell[1, 1] gamma = ((E_surf - E_per_atom_bulk * len(surface)) / (2.0 * area)) print('Surface energy of %s surface %.4f J/m^2\n' % (params.cleavage_plane, gamma / (units.J / units.m ** 2))) # ***** Setup crack slab supercell ***** # Now we will build the full crack slab system, # approximately matching requested width and height nx = int(params.width / unit_slab.cell[0, 0]) ny = int(params.height / unit_slab.cell[1, 1]) # make sure ny is even so slab is centered on a bond if ny % 2 == 1: ny += 1 # make a supercell of unit_slab crack_slab = unit_slab * (nx, ny, 1) # open up the cell along x and y by introducing some vaccum crack_slab.center(params.vacuum, axis=0) crack_slab.center(params.vacuum, axis=1) # centre the slab on the origin crack_slab.positions[:, 0] -= crack_slab.positions[:, 0].mean() crack_slab.positions[:, 1] -= crack_slab.positions[:, 1].mean() orig_width = (crack_slab.positions[:, 0].max() - crack_slab.positions[:, 0].min()) orig_height = (crack_slab.positions[:, 1].max() - crack_slab.positions[:, 1].min()) print(('Made slab with %d atoms, original width and height: %.1f x %.1f A^2' % (len(crack_slab), orig_width, orig_height))) top = crack_slab.positions[:, 1].max() bottom = crack_slab.positions[:, 1].min() left = crack_slab.positions[:, 0].min() right = crack_slab.positions[:, 0].max() # fix atoms in the top and bottom rows fixed_mask = ((abs(crack_slab.positions[:, 1] - top) < 1.0) | (abs(crack_slab.positions[:, 1] - bottom) < 1.0)) const = FixAtoms(mask=fixed_mask) crack_slab.set_constraint(const) print('Fixed %d atoms\n' % fixed_mask.sum()) # Save all calculated materials properties inside the Atoms object crack_slab.info['nneightol'] = 1.3 # nearest neighbour tolerance crack_slab.info['LatticeConstant'] = a0 crack_slab.info['C11'] = C[0, 0] crack_slab.info['C12'] = C[0, 1] crack_slab.info['C44'] = C[3, 3] crack_slab.info['YoungsModulus'] = E crack_slab.info['PoissonRatio_yx'] = nu crack_slab.info['SurfaceEnergy'] = gamma crack_slab.info['OrigWidth'] = orig_width crack_slab.info['OrigHeight'] = orig_height crack_slab.info['CrackDirection'] = params.crack_direction crack_slab.info['CleavagePlane'] = params.cleavage_plane crack_slab.info['CrackFront'] = params.crack_front crack_slab.info['cell_origin'] = -np.diag(crack_slab.cell)/2.0 crack_slab.set_array('fixed_mask', fixed_mask) ase.io.write('slab.xyz', crack_slab, format='extxyz') # ****** Apply initial strain ramp ***** strain = G_to_strain(params.initial_G, E, nu, orig_height) crack_slab.positions[:, 1] += thin_strip_displacement_y( crack_slab.positions[:, 0], crack_slab.positions[:, 1], strain, left + params.crack_seed_length, left + params.crack_seed_length + params.strain_ramp_length) print('Applied initial load: strain=%.4f, G=%.2f J/m^2' % (strain, params.initial_G / (units.J / units.m**2))) # ***** Relaxation of crack slab ***** # optionally, relax the slab, keeping top and bottom rows fixed if hasattr(params, 'relax_slab') and params.relax_slab: print('Relaxing slab...') crack_slab.set_calculator(params.calc) opt = FIRE(crack_slab) opt.run(fmax=params.relax_fmax) # Find initial position of crack tip crack_pos = find_tip_stress_field(crack_slab, calc=params.calc) print('Found crack tip at position %s' % crack_pos) crack_slab.info['strain'] = strain crack_slab.info['G'] = params.initial_G crack_slab.info['CrackPos'] = crack_pos # ******** Save output file ********** # Save results in extended XYZ format, including extra properties and info print('Writing crack slab to file "crack.xyz"') ase.io.write('crack.xyz', crack_slab, format='extxyz')
9,912
34.916667
78
py
matscipy
matscipy-master/scripts/fracture_mechanics/energy_barrier_multiple.py
# # Copyright 2014, 2021 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import os import sys import numpy as np import ase import ase.constraints import ase.io import ase.optimize from ase.data import atomic_numbers from ase.parallel import parprint import matscipy.fracture_mechanics.crack as crack ### sys.path += [ "." ] import params ### # Atom types used for outputting the crack tip position. ACTUAL_CRACK_TIP = 'Au' FITTED_CRACK_TIP = 'Ag' ### cryst = params.cryst.copy() crk = crack.CubicCrystalCrack(params.C11, params.C12, params.C44, params.crack_surface, params.crack_front) # Get Griffith's k1. k1g = crk.k1g(params.surface_energy) parprint('Griffith k1 = %f' % k1g) # Crack tip position. if hasattr(params, 'tip_x'): tip_x = params.tip_x else: tip_x = cryst.cell.diagonal()[0]/2 if hasattr(params, 'tip_y'): tip_y = params.tip_y else: tip_y = cryst.cell.diagonal()[1]/2 # Apply initial strain field. ase.io.write('cluster.xyz', cryst, format='extxyz') a = cryst.copy() ux, uy = crk.displacements(cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g) a.positions[:,0] += ux a.positions[:,1] += uy # Center notched configuration in simulation cell and ensure enough vacuum. oldr = a[0].position.copy() a.center(vacuum=params.vacuum, axis=0) a.center(vacuum=params.vacuum, axis=1) tip_x += a[0].position[0] - oldr[0] tip_y += a[0].position[1] - oldr[1] cryst.set_cell(a.cell) cryst.translate(a[0].position - oldr) ase.io.write('notch.xyz', a, format='extxyz') parprint('Initial tip position {0} {1}'.format(tip_x, tip_y)) # Groups mark the fixed region and the region use for fitting the crack tip. g = a.get_array('groups') # Assign calculator. a.set_calculator(params.calc) for j in range(params.n_bonds): bond1, bond2 = crack.find_tip_coordination(a) print 'Breaking tip bond {0}--{1}'.format(bond1, bond2) # Run crack calculation. for i, bond_length in enumerate(params.bond_lengths): parprint('=== bond_length = {0} ==='.format(bond_length)) xyz_file = 'bond_%d_%4d.xyz' % (j+1, int(bond_length*1000)) if os.path.exists(xyz_file): parprint('%s found, skipping' % xyz_file) a = ase.io.read(xyz_file) del a[np.logical_or(a.numbers == atomic_numbers[ACTUAL_CRACK_TIP], a.numbers == atomic_numbers[FITTED_CRACK_TIP])] a.set_calculator(params.calc) else: a.set_constraint(None) a.set_distance(bond1, bond2, bond_length) bond_length_constraint = ase.constraints.FixBondLength(bond1, bond2) # Atoms to be used for fitting the crack tip position. mask = g==1 # Optimize x and z position of crack tip. if hasattr(params, 'optimize_tip_position') and \ params.optimize_tip_position: old_x = tip_x+1.0 old_y = tip_y+1.0 while abs(tip_x-old_x) > 1e-6 and abs(tip_y-old_y) > 1e-6: b = cryst.copy() ux, uy = crk.displacements(cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g) b.positions[:,0] += ux b.positions[:,1] += uy a.set_constraint(None) a.positions[g==0] = b.positions[g==0] a.set_constraint([ase.constraints.FixAtoms(mask=g==0), bond_length_constraint]) parprint('Optimizing positions...') opt = ase.optimize.FIRE(a, logfile=None) opt.run(fmax=params.fmax) parprint('...done. Converged within {0} steps.' \ .format(opt.get_number_of_steps())) old_x = tip_x old_y = tip_y tip_x, tip_y = \ crk.crack_tip_position(a.positions[:,0], a.positions[:,1], cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g, mask=mask) parprint('New crack tip at {0} {1}'.format(tip_x, tip_y)) else: a.set_constraint([ase.constraints.FixAtoms(mask=g==0), bond_length_constraint]) parprint('Optimizing positions...') opt = ase.optimize.FIRE(a, logfile=None) opt.run(fmax=params.fmax) parprint('...done. Converged within {0} steps.' \ .format(opt.get_number_of_steps())) # Store forces. a.set_constraint(None) a.set_array('forces', a.get_forces()) # The target crack tip is marked by a gold atom. b = a.copy() b += ase.Atom(ACTUAL_CRACK_TIP, (tip_x, tip_y, b.cell.diagonal()[2]/2)) b.info['actual_crack_tip'] = (tip_x, tip_y, b.cell.diagonal()[2]/2) fit_x, fit_y = crk.crack_tip_position(a.positions[:,0], a.positions[:,1], cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g, mask=mask) parprint('Measured crack tip at %f %f' % (fit_x, fit_y)) # The fitted crack tip is marked by a silver atom. b += ase.Atom(FITTED_CRACK_TIP, (fit_x, fit_y, b.cell.diagonal()[2]/2)) b.info['fitted_crack_tip'] = (fit_x, fit_y, b.cell.diagonal()[2]/2) bond_dir = a[bond1].position - a[bond2].position bond_dir /= np.linalg.norm(bond_dir) force = np.dot(bond_length_constraint.get_constraint_force(), bond_dir) b.info['bond1'] = bond1 b.info['bond2'] = bond2 b.info['bond_length'] = bond_length b.info['force'] = force b.info['energy'] = a.get_potential_energy() b.info['cell_origin'] = [0, 0, 0] ase.io.write(xyz_file, b, format='extxyz')
8,330
38.29717
83
py
matscipy
matscipy-master/scripts/fracture_mechanics/sinclair_continuation.py
# # Copyright 2020-2021 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import matscipy; print(matscipy.__file__) import os import numpy as np import h5py import ase.io from ase.units import GPa from ase.constraints import FixAtoms from ase.optimize.precon import PreconLBFGS from matscipy import parameter from matscipy.elasticity import fit_elastic_constants from matscipy.fracture_mechanics.crack import CubicCrystalCrack, SinclairCrack from scipy.optimize import fsolve, fminbound import sys sys.path.insert(0, '.') import params calc = parameter('calc') fmax = parameter('fmax', 1e-3) max_steps = parameter('max_steps', 100) vacuum = parameter('vacuum', 10.0) flexible = parameter('flexible', True) continuation = parameter('continuation', False) ds = parameter('ds', 1e-2) nsteps = parameter('nsteps', 10) a0 = parameter('a0') # lattice constant k0 = parameter('k0', 1.0) extended_far_field = parameter('extended_far_field', False) alpha0 = parameter('alpha0', 0.0) # initial guess for crack position dump = parameter('dump', False) precon = parameter('precon', False) prerelax = parameter('prerelax', False) traj_file = parameter('traj_file', 'x_traj.h5') traj_interval = parameter('traj_interval', 1) direction = parameter('direction', +1) # compute elastic constants cryst = params.cryst.copy() cryst.pbc = True cryst.calc = calc C, C_err = fit_elastic_constants(cryst, symmetry=parameter('elastic_symmetry', 'triclinic')) crk = CubicCrystalCrack(parameter('crack_surface'), parameter('crack_front'), Crot=C/GPa) # Get Griffith's k1. k1g = crk.k1g(parameter('surface_energy')) print('Griffith k1 = %f' % k1g) cluster = params.cluster.copy() if continuation and not os.path.exists(traj_file): continuation = False if continuation: with h5py.File(traj_file, 'r') as hf: x = hf['x'] restart_index = parameter('restart_index', x.shape[0] - 1) x0 = x[restart_index-1, :] x1 = x[restart_index, :] k0 = x0[-1] / k1g sc = SinclairCrack(crk, cluster, calc, k0 * k1g, alpha=alpha0, vacuum=vacuum, variable_alpha=flexible, extended_far_field=extended_far_field) if not continuation: traj = None dk = parameter('dk', 1e-4) dalpha = parameter('dalpha', 1e-3) # reuse output from sinclair_crack.py if possible if os.path.exists(f'k_{int(k0 * 1000):04d}.xyz'): print(f'Reading atoms from k_{int(k0 * 1000):04d}.xyz') a = ase.io.read(f'k_{int(k0 * 1000):04d}.xyz') sc.set_atoms(a) mask = sc.regionI | sc.regionII if extended_far_field: mask = sc.regionI | sc.regionII | sc.regionIII # first use the CLE-only approximation`: define a function f_alpha0(k, alpha) def f(k, alpha): sc.k = k * k1g sc.alpha = alpha sc.update_atoms() return sc.get_crack_tip_force(mask=mask) # identify approximate range of stable k alpha_range = parameter('alpha_range', np.linspace(-a0, a0, 100)) k = k0 # initial guess for k alpha_k = [] for alpha in alpha_range: # look for solution to f(k, alpha) = 0 close to alpha = alpha (k,) = fsolve(f, k, args=(alpha,)) print(f'alpha={alpha:.3f} k={k:.3f} ') alpha_k.append((alpha, k)) alpha_k = np.array(alpha_k) kmin, kmax = alpha_k[:, 1].min(), alpha_k[:, 1].max() print(f'Estimated stable K range is {kmin} < k / k_G < {kmax}') # define a function to relax with static scheme at a given value of k # note that we use a looser fmax of 1e-3 and reduced max steps of 50 def g(k): print(f'Static minimisation with k={k}, alpha={alpha0}.') sc.k = k * k1g sc.alpha = alpha0 sc.variable_alpha = False sc.variable_k = False sc.update_atoms() atoms = sc.atoms.copy() atoms.calc = sc.calc atoms.set_constraint(FixAtoms(mask=~sc.regionI)) opt = PreconLBFGS(atoms, logfile=None) opt.run(fmax=1e-5) sc.set_atoms(atoms) f_alpha = sc.get_crack_tip_force(mask=mask) print(f'Static minimisation with k={k}, alpha={alpha0} --> f_alpha={f_alpha}') return abs(f_alpha) # minimise g(k) in [kmin, kmax] kopt, falpha_min, ierr, funccalls = fminbound(g, kmin, kmax, xtol=1e-8, full_output=True) print(f'Brent minimisation yields f_alpha={falpha_min} for k = {kopt} after {funccalls} calls') # re-optimize, first with static scheme, then flexible scheme sc.k = kopt * k1g sc.alpha = alpha0 sc.variable_alpha = False sc.optimize(ftol=1e-3, steps=max_steps) # finally, we revert to target fmax precision sc.variable_alpha = flexible sc.optimize(ftol=fmax, steps=max_steps) sc.atoms.write('x0.xyz') x0 = np.r_[sc.get_dofs(), k0 * k1g] alpha0 = sc.alpha # obtain a second solution x1 = (u_1, alpha_1, k_1) where # k_1 ~= k_0 and alpha_1 ~= alpha_0 print(f'Rescaling K_I from {sc.k} to {sc.k + dk * k1g}') k1 = k0 + dk sc.rescale_k(k1 * k1g) sc.atoms.write('x1.xyz') x1 = np.r_[sc.get_dofs(), k1 * k1g] # check crack tip didn't jump too far alpha1 = sc.alpha print(f'k0={k0}, k1={k1} --> alpha0={alpha0}, alpha1={alpha1}') assert abs(alpha1 - alpha0) < dalpha scv = SinclairCrack(crk, cluster, calc, k0 * k1g, alpha=alpha0, vacuum=vacuum, variable_alpha=flexible, variable_k=True, extended_far_field=extended_far_field) scv.arc_length_continuation(x0, x1, N=nsteps, ds=ds, ftol=fmax, steps=max_steps, direction=direction, continuation=continuation, traj_file=traj_file, traj_interval=traj_interval, precon=precon)
6,777
33.232323
99
py
matscipy
matscipy-master/scripts/fracture_mechanics/plot_cohesive_stress.py
# # Copyright 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import os import glob import sys import numpy as np import ase.io import ase.units import matplotlib.pyplot as plt ### sys.path += [ "." ] import params ### J_per_m2 = ase.units.J/ase.units.m**2 separation = [] bond_length = [] energy = [] for fn in sorted(glob.glob('separation_*.xyz')): a = ase.io.read(fn) separation += [ a.info['separation'] ] bond_length += [ a.info['bond_length'] ] energy += [ a.get_potential_energy() ] separation = np.array(separation) bond_length = np.array(bond_length) energy = np.array(energy) cryst = ase.io.read('cryst.xyz') surface = ase.io.read('surface.xyz') e_per_atom_bulk = cryst.get_potential_energy()/len(cryst) area = surface.get_volume() / surface.cell[1, 1] gamma = ((energy - e_per_atom_bulk * len(surface)) / (2.0 * area)) gamma_relaxed = ((surface.get_potential_energy() - e_per_atom_bulk * len(surface)) / (2.0 * area)) print 'gamma unrelaxed', gamma[-1]/J_per_m2, 'J/m^2' print 'gamma relaxed ', gamma_relaxed/J_per_m2, 'J/m^2' plt.clf() plt.subplot(211) dE_db = ((energy[1:] - energy[:-1])/(bond_length[1:] - bond_length[:-1]))/area dE_db /= ase.units.GPa plt.plot((bond_length[1:] + bond_length[:-1])/2., dE_db, 'b-') plt.ylabel(r'Cohesive stress / GPa') plt.xlim(bond_length[0], bond_length[-1]) plt.subplot(212) plt.plot(bond_length, gamma/J_per_m2, 'b-') plt.axhline(gamma_relaxed/J_per_m2, linestyle='--') plt.xlabel(r'Bond length / $\mathrm{\AA}$') plt.ylabel(r'Energy / J/m^2') plt.xlim(bond_length[0], bond_length[-1]) plt.ylim(0, 1.0) plt.draw() np.savetxt('gamma_bond_length.out', np.c_[bond_length, gamma])
3,398
31.371429
78
py
matscipy
matscipy-master/scripts/fracture_mechanics/energy_barrier.py
# # Copyright 2014-2015, 2021 Lars Pastewka (U. Freiburg) # 2017 Punit Patel (Warwick U.) # 2014-2016 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== # USAGE: # # Code imports the file 'params.py' from current working directory. params.py # contains simulation parameters. Some parameters can be omitted, see below. from math import sqrt import os import sys import numpy as np import ase from ase.constraints import FixConstraint import ase.io import ase.optimize from ase.data import atomic_numbers from ase.units import GPa from ase.geometry import find_mic import matscipy.fracture_mechanics.crack as crack from matscipy import parameter from matscipy.logger import screen from setup_crack import setup_crack ### import sys sys.path += ['.', '..'] import params class FixBondLength(FixConstraint): """Constraint object for fixing a bond length.""" removed_dof = 1 def __init__(self, a1, a2): """Fix distance between atoms with indices a1 and a2. If mic is True, follows the minimum image convention to keep constant the shortest distance between a1 and a2 in any periodic direction. atoms only needs to be supplied if mic=True. """ self.indices = [a1, a2] self.constraint_force = None def adjust_positions(self, atoms, new): p1, p2 = atoms.positions[self.indices] d, p = find_mic(np.array([p2 - p1]), atoms._cell, atoms._pbc) q1, q2 = new[self.indices] d, q = find_mic(np.array([q2 - q1]), atoms._cell, atoms._pbc) d *= 0.5 * (p - q) / q new[self.indices] = (q1 - d[0], q2 + d[0]) def adjust_forces(self, atoms, forces): d = np.subtract.reduce(atoms.positions[self.indices]) d, p = find_mic(np.array([d]), atoms._cell, atoms._pbc) d = d[0] d *= 0.5 * np.dot(np.subtract.reduce(forces[self.indices]), d) / p**2 self.constraint_force = d forces[self.indices] += (-d, d) def index_shuffle(self, atoms, ind): """Shuffle the indices of the two atoms in this constraint""" newa = [-1, -1] # Signal error for new, old in slice2enlist(ind, len(atoms)): for i, a in enumerate(self.indices): if old == a: newa[i] = new if newa[0] == -1 or newa[1] == -1: raise IndexError('Constraint not part of slice') self.indices = newa def get_constraint_force(self): """Return the (scalar) force required to maintain the constraint""" return self.constraint_force def get_indices(self): return self.indices def __repr__(self): return 'FixBondLength(%d, %d)' % tuple(self.indices) def todict(self): return {'name': 'FixBondLength', 'kwargs': {'a1': self.indices[0], 'a2': self.indices[1]}} ### Optimizer = ase.optimize.LBFGS Optimizer_steps_limit = 1000 # Atom types used for outputting the crack tip position. ACTUAL_CRACK_TIP = 'Au' FITTED_CRACK_TIP = 'Ag' ### logger = screen ### a, cryst, crk, k1g, tip_x, tip_y, bond1, bond2, boundary_mask, \ boundary_mask_bulk, tip_mask = setup_crack(logger=logger) ase.io.write('notch.xyz', a, format='extxyz') # Get general parameters basename = parameter('basename', 'energy_barrier') calc = parameter('calc') fmax = parameter('fmax', 0.01) # Get parameter used for fitting crack tip position optimize_tip_position = parameter('optimize_tip_position', False) residual_func = parameter('residual_func', crack.displacement_residual) _residual_func = residual_func tip_tol = parameter('tip_tol', 1e-4) tip_mixing_alpha = parameter('tip_mixing_alpha', 1.0) write_trajectory_during_optimization = parameter('write_trajectory_during_optimization', False) if optimize_tip_position: tip_x = (a.positions[bond1, 0] + a.positions[bond2, 0])/2 tip_y = (a.positions[bond1, 1] + a.positions[bond2, 1])/2 logger.pr('Optimizing tip position -> initially centering tip bond. ' 'Tip positions = {} {}'.format(tip_x, tip_y)) # Assign calculator. a.set_calculator(calc) sig_xx, sig_yy, sig_xy = crk.stresses(cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g) sig = np.vstack([sig_xx, sig_yy] + [ np.zeros_like(sig_xx)]*3 + [sig_xy]) eps = np.dot(crk.S, sig) # Do we have a converged run that we want to restart from? restart_from = parameter('restart_from', 'None') if restart_from == 'None': restart_from = None original_cell = a.get_cell().copy() # Run crack calculation. for i, bond_length in enumerate(params.bond_lengths): logger.pr('=== bond_length = {0} ==='.format(bond_length)) xyz_file = '%s_%4d.xyz' % (basename, int(bond_length*1000)) log_file = open('%s_%4d.log' % (basename, int(bond_length*1000)), 'w') if write_trajectory_during_optimization: traj_file = ase.io.NetCDFTrajectory('%s_%4d.nc' % \ (basename, int(bond_length*1000)), mode='w', atoms=a) traj_file.write() else: traj_file = None mask = None if restart_from is not None: fn = '{0}/{1}'.format(restart_from, xyz_file) if os.path.exists(fn): logger.pr('Restart relaxation from {0}'.format(fn)) b = ase.io.read(fn) mask = np.logical_or(b.numbers == atomic_numbers[ACTUAL_CRACK_TIP], b.numbers == atomic_numbers[FITTED_CRACK_TIP]) del b[mask] print(len(a), len(b)) print(a.numbers) print(b.numbers) assert np.all(a.numbers == b.numbers) a = b a.set_calculator(calc) tip_x, tip_y, dummy = a.info['actual_crack_tip'] a.set_cell(original_cell, scale_atoms=True) a.set_constraint(None) a.set_distance(bond1, bond2, bond_length) bond_length_constraint = FixBondLength(bond1, bond2) # Deformation gradient residual needs full Atoms object and therefore # special treatment here. if _residual_func == crack.deformation_gradient_residual: residual_func = lambda r0, crack, x, y, ref_x, ref_y, k, mask=None:\ _residual_func(r0, crack, x, y, a, ref_x, ref_y, cryst, k, params.cutoff, mask) # Optimize x and z position of crack tip. if optimize_tip_position: old_x = tip_x old_y = tip_y converged = False while not converged: #b = cryst.copy() u0x, u0y = crk.displacements(cryst.positions[:,0], cryst.positions[:,1], old_x, old_y, params.k1*k1g) ux, uy = crk.displacements(cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g) #b.positions[:,0] += ux #b.positions[:,1] += uy a.set_constraint(None) # Displace atom positions a.positions[:len(cryst),0] += ux-u0x a.positions[:len(cryst),1] += uy-u0y a.positions[bond1,0] -= ux[bond1]-u0x[bond1] a.positions[bond1,1] -= uy[bond1]-u0y[bond1] a.positions[bond2,0] -= ux[bond2]-u0x[bond2] a.positions[bond2,1] -= uy[bond2]-u0y[bond2] # Set bond length and boundary atoms explicitly to avoid numerical drift a.set_distance(bond1, bond2, bond_length) a.positions[boundary_mask,0] = \ cryst.positions[boundary_mask_bulk,0] + ux[boundary_mask_bulk] a.positions[boundary_mask,1] = \ cryst.positions[boundary_mask_bulk,1] + uy[boundary_mask_bulk] a.set_constraint([ase.constraints.FixAtoms(mask=boundary_mask), bond_length_constraint]) logger.pr('Optimizing positions...') opt = Optimizer(a, logfile=log_file) if traj_file: opt.attach(traj_file.write) opt.run(fmax=fmax, steps=Optimizer_steps_limit) logger.pr('...done. Converged within {0} steps.' \ .format(opt.get_number_of_steps())) old_x = tip_x old_y = tip_y tip_x, tip_y = crk.crack_tip_position(a.positions[:len(cryst),0], a.positions[:len(cryst),1], cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g, mask=tip_mask, residual_func=residual_func) dtip_x = tip_x-old_x dtip_y = tip_y-old_y logger.pr('- Fitted crack tip (before mixing) is at {:3.2f} {:3.2f} ' '(= {:3.2e} {:3.2e} from the former position).'.format(tip_x, tip_y, dtip_x, dtip_y)) tip_x = old_x + tip_mixing_alpha*dtip_x tip_y = old_y + tip_mixing_alpha*dtip_y logger.pr('- New crack tip (after mixing) is at {:3.2f} {:3.2f} ' '(= {:3.2e} {:3.2e} from the former position).'.format(tip_x, tip_y, tip_x-old_x, tip_y-old_y)) converged = np.asscalar(abs(dtip_x) < tip_tol and abs(dtip_y) < tip_tol) else: a.set_constraint([ase.constraints.FixAtoms(mask=boundary_mask), bond_length_constraint]) logger.pr('Optimizing positions...') opt = Optimizer(a, logfile=log_file) if traj_file: opt.attach(traj_file.write) opt.run(fmax=fmax, steps=Optimizer_steps_limit) logger.pr('...done. Converged within {0} steps.' \ .format(opt.get_number_of_steps())) # Store forces. a.set_constraint(None) a.set_array('forces', a.get_forces()) # Make a copy of the configuration. b = a.copy() # Fit crack tip (again), and get residuals. fit_x, fit_y, residuals = \ crk.crack_tip_position(a.positions[:len(cryst),0], a.positions[:len(cryst),1], cryst.positions[:,0], cryst.positions[:,1], tip_x, tip_y, params.k1*k1g, mask=mask, residual_func=residual_func, return_residuals=True) logger.pr('Measured crack tip at %f %f' % (fit_x, fit_y)) #b.set_array('residuals', residuals) # The target crack tip is marked by a gold atom. b += ase.Atom(ACTUAL_CRACK_TIP, (tip_x, tip_y, b.cell.diagonal()[2]/2)) b.info['actual_crack_tip'] = (tip_x, tip_y, b.cell.diagonal()[2]/2) # The fitted crack tip is marked by a silver atom. b += ase.Atom(FITTED_CRACK_TIP, (fit_x, fit_y, b.cell.diagonal()[2]/2)) b.info['fitted_crack_tip'] = (fit_x, fit_y, b.cell.diagonal()[2]/2) bond_dir = a[bond1].position - a[bond2].position bond_dir /= np.linalg.norm(bond_dir) force = np.dot(bond_length_constraint.get_constraint_force(), bond_dir) b.info['bond_length'] = bond_length b.info['force'] = force b.info['energy'] = a.get_potential_energy() b.info['cell_origin'] = [0, 0, 0] ase.io.write(xyz_file, b, format='extxyz') log_file.close() if traj_file: traj_file.close()
13,362
38.187683
116
py
matscipy
matscipy-master/scripts/fracture_mechanics/sinclair_crack.py
# # Copyright 2014, 2020 James Kermode (Warwick U.) # 2020 Arnaud Allera (U. Lyon 1) # 2014 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os import numpy as np import ase.io from ase.units import GPa from ase.constraints import FixAtoms from ase.optimize.precon import PreconLBFGS from matscipy import parameter from matscipy.elasticity import fit_elastic_constants from matscipy.fracture_mechanics.crack import CubicCrystalCrack, SinclairCrack import sys sys.path.insert(0, '.') import params calc = parameter('calc') fmax = parameter('fmax', 1e-3) vacuum = parameter('vacuum', 10.0) flexible = parameter('flexible', True) extended_far_field = parameter('extended_far_field', False) k0 = parameter('k0', 1.0) alpha0 = parameter('alpha0', 0.0) # initial guess for crack position dump = parameter('dump', False) precon = parameter('precon', False) prerelax = parameter('prerelax', False) lbfgs = parameter('lbfgs', not flexible) # use LBGS by default if not flexible # compute elastic constants cryst = params.cryst.copy() cryst.pbc = True cryst.calc = calc C, C_err = fit_elastic_constants(cryst, symmetry=parameter('elastic_symmetry', 'triclinic')) crk = CubicCrystalCrack(parameter('crack_surface'), parameter('crack_front'), Crot=C/GPa) # Get Griffith's k1. k1g = crk.k1g(parameter('surface_energy')) print('Griffith k1 = %f' % k1g) cluster = params.cluster.copy() sc = SinclairCrack(crk, cluster, calc, k0 * k1g, alpha=alpha0, variable_alpha=flexible, vacuum=vacuum, extended_far_field=extended_far_field) nsteps = parameter('nsteps') k1_range = parameter('k1_range', np.linspace(0.8, 1.2, nsteps)) ks = list(k1_range) ks_out = [] alphas = [] max_steps = parameter('max_steps', 10) fit_alpha = parameter('fit_alpha', False) for i, k in enumerate(ks): restart_file = parameter('restart_file', f'k_{int(k * 1000):04d}.xyz') if os.path.exists(restart_file): print(f'Restarting from {restart_file}') if restart_file.endswith('.xyz'): a = ase.io.read(restart_file) sc.set_atoms(a) elif restart_file.endswith('.txt'): x = np.loadtxt(restart_file) if len(x) == len(sc): sc.set_dofs(x) elif len(x) == len(sc) + 1: sc.variable_k = True sc.set_dofs(x) sc.variable_k = False elif len(x) == len(sc) + 2: sc.variable_alpha = True sc.variable_k = True sc.set_dofs(x) sc.variable_alpha = False sc.variable_k = False else: raise RuntimeError('cannot guess how to restart with' f' {len(x)} variables for {len(self)} DoFs') else: raise ValueError(f"don't know how to restart from {restart_file}") else: sc.rescale_k(k * k1g) if fit_alpha: sc.alpha, = sc.fit_cle(variable_alpha=True, variable_k=False) print(f'Fitted value of alpha: {sc.alpha}') print(f'k = {sc.k / k1g} * k1g') print(f'alpha = {sc.alpha}') if lbfgs: print('Optimizing with LBFGS') atoms = sc.atoms.copy() atoms.calc = sc.calc atoms.set_constraint(FixAtoms(mask=np.logical_not(sc.regionI))) opt = PreconLBFGS(atoms) opt.run(fmax=fmax) sc.set_atoms(atoms) else: if prerelax: print('Pre-relaxing with Conjugate-Gradients') sc.optimize(ftol=1e-5, steps=max_steps, dump=dump, method='cg') sc.optimize(fmax, steps=max_steps, dump=dump, precon=precon, method='krylov') if flexible: print(f'Optimized alpha = {sc.alpha:.3f}') ks_out.append(k) alphas.append(sc.alpha) a = sc.atoms a.get_forces() ase.io.write(f'k_{int(k * 1000):04d}.xyz', a) with open('x.txt', 'a') as fh: np.savetxt(fh, [sc.get_dofs()]) np.savetxt('k_vs_alpha.txt', np.c_[ks_out, alphas])
4,945
31.973333
79
py
matscipy
matscipy-master/scripts/diffusion/rms.py
# # Copyright 2019, 2021 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import sys import numpy as np from ase.data import chemical_symbols from ase.io import NetCDFTrajectory from matscipy.neighbours import mic ### traj = NetCDFTrajectory(sys.argv[1]) ref_frame = traj[0] individual_elements = set(ref_frame.numbers) s = '#{:>9s}'.format('frame') if 'time' in ref_frame.info: s = '{} {:>10s}'.format(s, 'time') s = '{} {:>10s}'.format(s, 'tot. rms') for element in individual_elements: s = '{} {:>10s}'.format(s, 'rms ({})'.format(chemical_symbols[element])) print(s) last_frame = traj[0] displacements = np.zeros_like(ref_frame.positions) for i, frame in enumerate(traj[1:]): last_frame.set_cell(frame.cell, scale_atoms=True) cur_displacements = frame.positions - last_frame.positions cur_displacements = mic(cur_displacements, frame.cell, frame.pbc) displacements += cur_displacements s = '{:10}'.format(i+1) if 'time' in frame.info: s = '{} {:10.6}'.format(s, frame.info['time']) s = '{} {:10.6}'.format(s, np.sqrt((displacements**2).mean())) for element in individual_elements: s = '{} {:10.6}'.format(s, np.sqrt( (displacements[frame.numbers == element]**2).mean())) print(s) last_frame = frame
2,011
30.936508
76
py
matscipy
matscipy-master/scripts/glasses/quench.py
# # Copyright 2016-2019, 2021 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os import signal import sys import numpy as np import ase from ase.atoms import string2symbols from ase.io import read, write from ase.io.trajectory import Trajectory from ase.optimize import FIRE from ase.md import Langevin from ase.units import mol, fs, kB from matscipy import parameter ### def handle_sigusr2(signum, frame): # Just shutdown and hope that there is no current write operation print("Received SIGUSR2. Terminating...") sys.exit(0) signal.signal(signal.SIGUSR2, handle_sigusr2) ### def random_solid(els, density, sx=None, sy=None): if isinstance(els, str): syms = string2symbols(els) else: syms = "" for sym, n in els: syms += n*sym r = np.random.rand(len(syms), 3) a = ase.Atoms(syms, positions=r, cell=[1,1,1], pbc=True) mass = np.sum(a.get_masses()) if sx is not None and sy is not None: sz = ( 1e24*mass/(density*mol) )/(sx*sy) a.set_cell([sx,sy,sz], scale_atoms=True) else: a0 = ( 1e24*mass/(density*mol) )**(1./3) a.set_cell([a0,a0,a0], scale_atoms=True) a.set_initial_charges([0]*len(a)) return a ### # For coordination counting cutoff = 1.85 els = parameter('stoichiometry') densities = parameter('densities') T1 = parameter('T1', 5000*kB) T2 = parameter('T2', 300*kB) dt1 = parameter('dt1', 0.1*fs) dt2 = parameter('dt2', 0.1*fs) tau1 = parameter('tau1', 5000*fs) tau2 = parameter('tau2', 500*fs) dtdump = parameter('dtdump', 100*fs) teq = parameter('teq', 50e3*fs) tqu = parameter('tqu', 20e3*fs) nsteps_relax = parameter('nsteps_relax', 10000) ### quick_calc = parameter('quick_calc') calc = parameter('calc') ### for _density in densities: try: density, sx, sy = _density except: density = _density sx = sy = None print('density =', density) initial_fn = 'density_%2.1f-initial.traj' % density liquid_fn = 'density_%2.1f-liquid.traj' % density liquid_final_fn = 'density_%2.1f-liquid.final.traj' % density quench_fn = 'density_%2.1f-quench.traj' % density quench_final_fn = 'density_%2.1f-quench.final.traj' % density print('=== LIQUID ===') if not os.path.exists(liquid_final_fn): if not os.path.exists(liquid_fn): print('... creating new solid ...') a = random_solid(els, density, sx=sx, sy=sy) n = a.get_atomic_numbers().copy() # Relax with the quick potential a.set_atomic_numbers([6]*len(a)) a.set_calculator(quick_calc) FIRE(a, downhill_check=True).run(fmax=1.0, steps=nsteps_relax) a.set_atomic_numbers(n) write(initial_fn, a) else: print('... reading %s ...' % liquid_fn) a = read(liquid_fn) # Thermalize with the slow (but correct) potential a.set_calculator(calc) traj = Trajectory(liquid_fn, 'a', a) dyn = Langevin(a, dt1, T1, 1.0/tau1, logfile='-', loginterval=int(dtdump/dt1)) dyn.attach(traj.write, interval=int(dtdump/dt1)) # every 100 fs nsteps = int(teq/dt1)-len(traj)*int(dtdump/dt1) print('Need to run for further {} steps to reach total of {} steps.'.format(nsteps, int(teq/dt1))) if nsteps <= 0: nsteps = 1 dyn.run(nsteps) traj.close() # Write snapshot write(liquid_final_fn, a) else: print('... reading %s ...' % liquid_final_fn) a = read(liquid_final_fn) a.set_calculator(calc) print('=== QUENCH ===') if not os.path.exists(quench_final_fn): if os.path.exists(quench_fn): print('... reading %s ...' % quench_fn) a = read(quench_fn) a.set_calculator(calc) # 10ps Langevin quench to 300K traj = Trajectory(quench_fn, 'a', a) dyn = Langevin(a, dt2, T2, 1.0/tau2, logfile='-', loginterval=200) dyn.attach(traj.write, interval=int(dtdump/dt2)) # every 100 fs nsteps = int(tqu/dt2)-len(traj)*int(dtdump/dt2) print('Need to run for further {} steps to reach total of {} steps.'.format(nsteps, int(teq/dt1))) dyn.run(nsteps) # Write snapshot write(quench_final_fn, a) open('DONE_%2.1f' % density, 'w')
5,123
29.319527
106
py
matscipy
matscipy-master/tests/test_io.py
# # Copyright 2014-2016, 2021 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # 2022 Lucas Frérot (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # Adrien Gola, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np from ase.io import read from matscipy.io import loadtbl, savetbl from matscipy.io.lammpsdata import LAMMPSData, read_molecules_from_lammps_data from matscipy.molecules import Molecules import pytest import matscipytest class TestEAMIO(matscipytest.MatSciPyTestCase): def test_savetbl_loadtbl(self): n = 123 a = np.random.random(n) b = np.random.random(n) poe = np.random.random(n) savetbl('test.out', a=a, b=b, poe=poe) data = loadtbl('test.out') self.assertArrayAlmostEqual(a, data['a']) self.assertArrayAlmostEqual(b, data['b']) self.assertArrayAlmostEqual(poe, data['poe']) def test_savetbl_loadtbl_text(self): n = 12 a = np.random.random(n) b = np.random.random(n) t = ['a'*(i+1) for i in range(n)] savetbl('test2.out', a=a, b=b, t=t) a2, t2, b2 = loadtbl('test2.out', usecols=['a', 't', 'b'], types={'t': np.str_}) self.assertArrayAlmostEqual(a, a2) self.assertArrayAlmostEqual(b, b2) assert (t == t2).all() ### @pytest.fixture def lammps_data(tmp_path): filename = tmp_path / "lammps_text.data" data = LAMMPSData(style='full') data['atoms'] = [ [0, 0, 0], [0, 0, 1], [1.1, 2, 1.1] ] data['velocities'] = [ [0, 0, 1], [0, 1, 0], [1, 0, 0], ] data['atom types'] = [1, 1, 2] data['atoms']['charge'] = [1, -1, 1] data['atoms']['mol'] = 1 data['masses'] = [2, 3] data['bonds'] = [ [1, 3], [2, 3], ] data['bond types'] = [1, 2] data['angles'] = [ [1, 2, 3], [2, 3, 1], ] data['angle types'] = [1, 2] data.ranges = [[-1, 1], [-1, 1], [-1, 1]] data.write(filename) return data, filename def test_read_write_lammps_data(lammps_data): data, filename = lammps_data read_data = LAMMPSData(style='full') read_data.read(filename) assert np.all(np.array(data.ranges) == np.array(read_data.ranges)) assert np.all(data['atoms'] == read_data['atoms']) assert np.all(data['bonds'] == read_data['bonds']) assert np.all(data['angles'] == read_data['angles']) assert np.all(data['masses'] == read_data['masses']) assert np.all(data['velocities'] == read_data['velocities']) @pytest.fixture def mols_from_lammps_data(lammps_data): # Correct for type offset for label in ["bonds", "angles", "dihedrals"]: lammps_data[0][label]["atoms"] -= 1 return lammps_data[0], read_molecules_from_lammps_data(lammps_data[1]) @pytest.fixture def mols_from_atoms(lammps_data): data, filename = lammps_data atoms = read(filename, format='lammps-data', sort_by_id=True, units='metal', style='full') # Correct for type offset for label in ["bonds", "angles", "dihedrals"]: data[label]["atoms"] -= 1 return data, Molecules.from_atoms(atoms) def test_read_molecules_from_lammps_data(mols_from_lammps_data): data, mols = mols_from_lammps_data data["angles"]["atoms"] = data["angles"]["atoms"][:, (1, 0, 2)] assert np.all(data["bonds"] == mols.bonds) assert np.all(data["angles"] == mols.angles) assert np.all(data["dihedrals"] == mols.dihedrals) def test_read_molecules_from_atoms(mols_from_atoms): data, mols = mols_from_atoms data["angles"]["atoms"] = data["angles"]["atoms"][:, (1, 0, 2)] assert np.all(data["bonds"] == mols.bonds) assert np.all(data["angles"] == mols.angles) assert np.all(data["dihedrals"] == mols.dihedrals) if __name__ == '__main__': unittest.main()
5,601
30.47191
88
py
matscipy
matscipy-master/tests/test_opls_io.py
# # Copyright 2023 Andreas Klemenz (Fraunhofer IWM) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import sys import unittest import matscipytest import numpy as np import ase import ase.io import matscipy.opls import matscipy.io.opls import ase.calculators.lammpsrun class TestOPLSIO(matscipytest.MatSciPyTestCase): def test_read_extended_xyz(self): struct = matscipy.io.opls.read_extended_xyz('opls_extxyz.xyz') self.assertIsInstance(struct, matscipy.opls.OPLSStructure) self.assertListEqual(list(struct.numbers), [1, 1]) self.assertArrayAlmostEqual( struct.positions, [[4.5, 5.0, 5.0], [5.5, 5.0, 5.0]], tol=0.01 ) self.assertListEqual(list(struct.get_array('molid')), [1, 1]) self.assertListEqual(list(struct.types), ['H1']) self.assertListEqual(list(struct.get_array('type')), ['H1', 'H1']) self.assertListEqual(list(struct.get_array('tags')), [0, 0]) def test_read_block(self): data = matscipy.io.opls.read_block('opls_parameters.in', 'Dihedrals') self.assertDictionariesEqual( data, {'H1-C1-C1-H1': [0.00, 0.00, 0.01, 0.00]}, ignore_case=False ) with self.assertRaises(RuntimeError): matscipy.io.opls.read_block('opls_parameters.in', 'Charges') def test_read_cutoffs(self): cutoffs = matscipy.io.opls.read_cutoffs('opls_cutoffs.in') self.assertIsInstance(cutoffs, matscipy.opls.CutoffList) self.assertDictionariesEqual( cutoffs.nvh, {'C1-C1': 1.85, 'C1-H1': 1.15}, ignore_case=False ) def test_read_parameter_file(self): cutoffs, ljq, bonds, angles, dihedrals = matscipy.io.opls.read_parameter_file('opls_parameters.in') self.assertIsInstance(cutoffs, matscipy.opls.CutoffList) self.assertDictionariesEqual( cutoffs.nvh, {'C1-C1': 1.85, 'C1-H1': 1.15, 'H1-H1': 0.0}, ignore_case=False ) self.assertIsInstance(ljq, dict) self.assertDictionariesEqual( ljq, {'C1': [0.001, 3.500, -0.010], 'H1': [0.001, 2.500, 0.010]}, ignore_case=False ) self.assertIsInstance(ljq.lj_cutoff, float) self.assertIsInstance(ljq.c_cutoff, float) self.assertAlmostEqual(ljq.lj_cutoff, 12.0, places=2) self.assertAlmostEqual(ljq.c_cutoff, 15.0, places=2) self.assertIsInstance(ljq.lj_pairs, dict) self.assertDictionariesEqual( ljq.lj_pairs, {'C1-H1': [0.001, 3.4, 11.0]}, ignore_case=False ) self.assertIsInstance(bonds, matscipy.opls.BondData) self.assertDictionariesEqual( bonds.nvh, {'C1-C1': [10.0, 1.0], 'C1-H1': [10.0, 1.0]}, ignore_case=False ) self.assertIsInstance(angles, matscipy.opls.AnglesData) self.assertDictionariesEqual( angles.nvh, {'H1-C1-C1': [1.0, 100.0], 'H1-C1-H1': [1.0, 100.0]}, ignore_case=False ) self.assertIsInstance(dihedrals, matscipy.opls.DihedralsData) self.assertDictionariesEqual( dihedrals.nvh, {'H1-C1-C1-H1': [0.00, 0.00, 0.01, 0.00]}, ignore_case=False ) def test_read_lammps_data(self): test_structure = matscipy.io.opls.read_lammps_data('opls_test.atoms', 'opls_test.parameters') self.assertArrayAlmostEqual(test_structure.cell, [[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]], tol=0.01) self.assertEqual(len(test_structure), 4) self.assertListEqual(list(test_structure.numbers), [1, 6, 6, 1]) self.assertArrayAlmostEqual(test_structure.positions, [[3.5, 5.0, 5.0], [4.5, 5.0, 5.0], [5.5, 5.0, 5.0], [6.5, 5.0, 5.0]], tol=0.01) test_velocities = ase.calculators.lammpsrun.convert( test_structure.get_velocities(), 'velocity', 'ASE', 'metal' ) self.assertArrayAlmostEqual(test_velocities, [[0.1, 0.2, 0.3], [0.0, 0.0, 0.0], [0.4, 0.5, 0.6], [0.0, 0.0, 0.0] ], tol=0.01) self.assertArrayAlmostEqual(test_structure.get_masses(), [1.008, 12.011, 12.011, 1.008], tol=0.0001) self.assertArrayAlmostEqual(test_structure.get_charges(), [0.01, -0.01, -0.01, 0.01], tol=0.001) self.assertListEqual( list(test_structure.get_array('molid')), [1, 1, 1, 1] ) self.assertEqual(len(test_structure.get_types()), 2) self.assertTrue('C1' in test_structure.get_types()) self.assertTrue('H1' in test_structure.get_types()) self.assertEqual(len(test_structure.bond_types), 2) self.assertTrue('C1-C1' in test_structure.bond_types) self.assertTrue('C1-H1' in test_structure.bond_types or 'H1-C1' in test_structure.bond_types) self.assertTupleEqual(test_structure.bond_list.shape, (3, 3)) self.assertTrue( (test_structure.bond_list[0] == [0, 0, 1]).all() or (test_structure.bond_list[0] == [0, 1, 0]).all() ) self.assertTrue( (test_structure.bond_list[1] == [1, 1, 2]).all() or (test_structure.bond_list[1] == [1, 2, 1]).all() ) self.assertTrue( (test_structure.bond_list[2] == [0, 2, 3]).all() or (test_structure.bond_list[2] == [0, 3, 2]).all() ) self.assertEqual(len(test_structure.ang_types), 1) self.assertTrue('H1-C1-C1' in test_structure.ang_types or 'C1-C1-H1' in test_structure.ang_types) self.assertTupleEqual(test_structure.ang_list.shape, (2, 4)) self.assertTrue( (test_structure.ang_list[0] == [0, 0, 1, 2]).all() or (test_structure.ang_list[0] == [0, 2, 1, 0]).all() ) self.assertTrue( (test_structure.ang_list[1] == [0, 1, 2, 3]).all() or (test_structure.ang_list[1] == [0, 3, 2, 1]).all() ) self.assertEqual(len(test_structure.dih_types), 1) self.assertListEqual(test_structure.dih_types, ['H1-C1-C1-H1']) self.assertTupleEqual(test_structure.dih_list.shape, (1, 5)) self.assertTrue( (test_structure.dih_list[0] == [0, 0, 1, 2, 3]).all() or (test_structure.dih_list[0] == [0, 3, 2, 1, 0]).all() ) def test_write_lammps_atoms(self): c2h2 = ase.Atoms('HC2H', cell=[10., 10., 10.]) c2h2.set_positions([ [0., 0., 0.], [1., 0., 0.], [2., 0., 0.], [3., 0., 0.] ]) opls_c2h2 = matscipy.opls.OPLSStructure(c2h2) opls_c2h2.set_types(['H1', 'C1', 'C1', 'H1']) cutoffs, ljq, bonds, angles, dihedrals = matscipy.io.opls.read_parameter_file('opls_parameters.in') opls_c2h2.set_cutoffs(cutoffs) opls_c2h2.set_atom_data(ljq) opls_c2h2.get_bonds(bonds) opls_c2h2.get_angles(angles) opls_c2h2.get_dihedrals(dihedrals) matscipy.io.opls.write_lammps_atoms('temp', opls_c2h2) matscipy.io.opls.write_lammps_definitions('temp', opls_c2h2) # Read written structure c2h2_written = matscipy.io.opls.read_lammps_data('temp.atoms', 'temp.opls') self.assertArrayAlmostEqual(c2h2_written.cell, [[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]], tol=0.01) self.assertEqual(len(c2h2_written), 4) self.assertListEqual(list(c2h2_written.numbers), [1, 6, 6, 1]) self.assertArrayAlmostEqual(c2h2_written.positions, [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], tol=0.01) self.assertArrayAlmostEqual(c2h2_written.get_velocities(), np.zeros([4, 3], dtype=float), tol=0.01) self.assertArrayAlmostEqual(c2h2_written.get_masses(), [1.008, 12.011, 12.011, 1.008], tol=0.0001) self.assertArrayAlmostEqual(c2h2_written.get_charges(), [0.01, -0.01, -0.01, 0.01], tol=0.001) self.assertListEqual(list(c2h2_written.get_array('molid')), [1, 1, 1, 1]) self.assertEqual(len(c2h2_written.get_types()), 2) self.assertTrue('C1' in c2h2_written.get_types()) self.assertTrue('H1' in c2h2_written.get_types()) self.assertEqual(len(c2h2_written.bond_types), 2) self.assertTrue('C1-C1' in c2h2_written.bond_types) self.assertTrue('C1-H1' in c2h2_written.bond_types or 'H1-C1' in c2h2_written.bond_types) self.assertTupleEqual(c2h2_written.bond_list.shape, (3, 3)) bonds = c2h2_written.bond_list[:, 1:].tolist() self.assertTrue([0, 1] in bonds or [1, 0] in bonds) self.assertTrue([1, 2] in bonds or [2, 1] in bonds) self.assertTrue([2, 3] in bonds or [3, 2] in bonds) self.assertEqual(len(c2h2_written.ang_types), 1) self.assertTrue('H1-C1-C1' in c2h2_written.ang_types or 'C1-C1-H1' in c2h2_written.ang_types) self.assertTupleEqual(c2h2_written.ang_list.shape, (2, 4)) angles = c2h2_written.ang_list[:, 1:].tolist() self.assertTrue([0, 1, 2] in angles or [2, 1, 0] in angles) self.assertTrue([1, 2, 3] in angles or [3, 2, 1] in angles) self.assertEqual(len(c2h2_written.dih_types), 1) self.assertListEqual(c2h2_written.dih_types, ['H1-C1-C1-H1']) self.assertTupleEqual(c2h2_written.dih_list.shape, (1, 5)) self.assertTrue( (c2h2_written.dih_list[0] == [0, 0, 1, 2, 3]).all() or (c2h2_written.dih_list[0] == [0, 3, 2, 1, 0]).all() ) def test_write_lammps_definitions(self): c2h2 = ase.Atoms('HC2H', cell=[10., 10., 10.]) c2h2.set_positions( [[0., 0., 0.], [1., 0., 0.], [2., 0., 0.], [3., 0., 0.]] ) opls_c2h2 = matscipy.opls.OPLSStructure(c2h2) opls_c2h2.set_types(['H1', 'C1', 'C1', 'H1']) cutoffs, ljq, bonds, angles, dihedrals = matscipy.io.opls.read_parameter_file('opls_parameters.in') opls_c2h2.set_cutoffs(cutoffs) opls_c2h2.set_atom_data(ljq) opls_c2h2.get_bonds(bonds) opls_c2h2.get_angles(angles) opls_c2h2.get_dihedrals(dihedrals) matscipy.io.opls.write_lammps_definitions('temp', opls_c2h2) # Read written parameters pair_coeff = [] bond_coeff = [] angle_coeff = [] dihedral_coeff = [] charges = [] with open('temp.opls', 'r') as fileobj: for line in fileobj.readlines(): if line.startswith('pair_style'): lj_cutoff = line.split()[2] q_cutoff = line.split()[3] elif line.startswith('pair_coeff'): pair_coeff.append(line.split()) elif line.startswith('bond_coeff'): bond_coeff.append(line.split()) elif line.startswith('angle_coeff'): angle_coeff.append(line.split()) elif line.startswith('dihedral_coeff'): dihedral_coeff.append(line.split()) elif len(line.split()) > 3: if line.split()[3] == 'charge': charges.append(line.split()) self.assertEqual(len(charges), 2) for charge in charges: if charge[6] == 'C1': self.assertAlmostEqual(float(charge[4]), -0.01, places=2) elif charge[6] == 'H1': self.assertAlmostEqual(float(charge[4]), 0.01, places=2) self.assertAlmostEqual(float(lj_cutoff), 12.0, places=1) self.assertAlmostEqual(float(q_cutoff), 15.0, places=1) self.assertEqual(len(pair_coeff), 3) for pair in pair_coeff: if pair[6] == 'C1': self.assertAlmostEqual(float(pair[3]), 0.001, places=3) self.assertAlmostEqual(float(pair[4]), 3.5, places=1) elif pair[6] == 'H1': self.assertAlmostEqual(float(pair[3]), 0.001, places=3) self.assertAlmostEqual(float(pair[4]), 2.5, places=1) elif pair[7] == 'H1-C1' or pair[7] == 'C1-H1': self.assertAlmostEqual(float(pair[3]), 0.001, places=3) self.assertAlmostEqual(float(pair[4]), 3.4, places=1) self.assertAlmostEqual(float(pair[5]), 11.0, places=1) self.assertEqual(len(bond_coeff), 2) for bond in bond_coeff: if bond[5] == 'C1-C1': self.assertAlmostEqual(float(bond[2]), 10.0, places=1) self.assertAlmostEqual(float(bond[3]), 1.0, places=1) elif bond[5] == 'H1-C1' or bond[5] == 'C1-H1': self.assertAlmostEqual(float(bond[2]), 10.0, places=1) self.assertAlmostEqual(float(bond[3]), 1.0, places=1) self.assertEqual(len(angle_coeff), 1) self.assertAlmostEqual(float(angle_coeff[0][2]), 1.0, places=1) self.assertAlmostEqual(float(angle_coeff[0][3]), 100.0, places=1) self.assertEqual(len(dihedral_coeff), 1) self.assertAlmostEqual(float(dihedral_coeff[0][2]), 0.0, places=1) self.assertAlmostEqual(float(dihedral_coeff[0][3]), 0.0, places=1) self.assertAlmostEqual(float(dihedral_coeff[0][4]), 0.01, places=2) self.assertAlmostEqual(float(dihedral_coeff[0][5]), 0.0, places=1) if __name__ == '__main__': unittest.main()
15,707
40.013055
107
py
matscipy
matscipy-master/tests/test_ring_statistics.py
# # Copyright 2014-2015, 2017, 2020-2021 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import ase.build import ase.io import ase.lattice.hexagonal import matscipytest from matscipy.neighbours import neighbour_list from matscipy.rings import ring_statistics from matscipy.ffi import distances_on_graph, find_sp_rings ### class TestNeighbours(matscipytest.MatSciPyTestCase): def test_single_ring(self): a = ase.build.molecule('C6H6') a = a[a.numbers==6] a.center(vacuum=5) i, j, r = neighbour_list('ijD', a, 1.85) d = distances_on_graph(i, j) self.assertEqual(d.shape, (6,6)) self.assertArrayAlmostEqual(d-d.T, np.zeros_like(d)) dcheck = np.arange(len(a)) dcheck = np.abs(dcheck.reshape(1,-1)-dcheck.reshape(-1,1)) dcheck = np.where(dcheck > len(a)/2, len(a)-dcheck, dcheck) self.assertArrayAlmostEqual(d, dcheck) r = find_sp_rings(i, j, r, d) self.assertArrayAlmostEqual(r, [0,0,0,0,0,0,1]) def test_two_rings(self): a = ase.build.molecule('C6H6') a = a[a.numbers==6] a.center(vacuum=10) b = a.copy() b.translate([5.0,5.0,5.0]) a += b r = ring_statistics(a, 1.85) self.assertArrayAlmostEqual(r, [0,0,0,0,0,0,2]) def test_many_rings(self): a = ase.lattice.hexagonal.Graphite('C', latticeconstant=(2.5, 10.0), size=[2,2,1]) r = ring_statistics(a, 1.85) self.assertArrayAlmostEqual(r, [0,0,0,0,0,0,8]) def test_pbc(self): r = np.arange(6) r = np.transpose([r,np.zeros_like(r),np.zeros_like(r)]) a = ase.Atoms('6C', positions=r, cell=[6,6,6], pbc=True) r = ring_statistics(a, 1.5) self.assertEqual(len(r), 0) def test_aC(self): a = ase.io.read('aC.cfg') r = ring_statistics(a, 1.85, maxlength=16) self.assertArrayAlmostEqual(r, [0,0,0,0,4,813,2678,1917,693,412,209,89, 21,3]) ### if __name__ == '__main__': unittest.main()
3,896
32.886957
79
py
matscipy
matscipy-master/tests/test_hydrogenate.py
# # Copyright 2014-2015, 2020 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import ase import ase.io as io from ase.lattice.cubic import Diamond import matscipytest from matscipy.hydrogenate import hydrogenate from matscipy.neighbours import neighbour_list ### class TestNeighbours(matscipytest.MatSciPyTestCase): def test_hydrogenate(self): a = Diamond('Si', size=[2,2,1]) b = hydrogenate(a, 2.85, 1.0, mask=[True,True,False], vacuum=5.0) # Check if every atom is fourfold coordinated syms = np.array(b.get_chemical_symbols()) c = np.bincount(neighbour_list('i', b, 2.4)) self.assertTrue((c[syms!='H']==4).all()) ### if __name__ == '__main__': unittest.main()
2,522
34.041667
73
py
matscipy
matscipy-master/tests/test_neighbours.py
# # Copyright 2014-2015, 2017-2021 Lars Pastewka (U. Freiburg) # 2020 Jonas Oldenstaedt (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import ase import ase.io as io import ase.lattice.hexagonal from ase.build import bulk, molecule import matscipytest from matscipy.neighbours import ( neighbour_list, first_neighbours, triplet_list, mic, CutoffNeighbourhood, MolecularNeighbourhood, get_jump_indicies, ) from matscipy.fracture_mechanics.idealbrittlesolid import triangular_lattice_slab from matscipy.molecules import Molecules ### class TestNeighbours(matscipytest.MatSciPyTestCase): def test_neighbour_list(self): for pbc in [True, False, [True, False, True]]: a = io.read('aC.cfg') a.set_pbc(pbc) j, dr, i, abs_dr, shift = neighbour_list("jDidS", a, 1.85) self.assertTrue((np.bincount(i) == np.bincount(j)).all()) r = a.get_positions() dr_direct = mic(r[j]-r[i], a.cell) self.assertArrayAlmostEqual(r[j]-r[i]+shift.dot(a.cell), dr_direct) abs_dr_from_dr = np.sqrt(np.sum(dr*dr, axis=1)) abs_dr_direct = np.sqrt(np.sum(dr_direct*dr_direct, axis=1)) self.assertTrue(np.all(np.abs(abs_dr-abs_dr_from_dr) < 1e-12)) self.assertTrue(np.all(np.abs(abs_dr-abs_dr_direct) < 1e-12)) self.assertTrue(np.all(np.abs(dr-dr_direct) < 1e-12)) def test_neighbour_list_atoms_outside_box(self): for pbc in [True, False, [True, False, True]]: a = io.read('aC.cfg') a.set_pbc(pbc) a.positions[100, :] += a.cell[0, :] a.positions[200, :] += a.cell[1, :] a.positions[300, :] += a.cell[2, :] j, dr, i, abs_dr, shift = neighbour_list("jDidS", a, 1.85) self.assertTrue((np.bincount(i) == np.bincount(j)).all()) r = a.get_positions() dr_direct = mic(r[j]-r[i], a.cell) self.assertArrayAlmostEqual(r[j]-r[i]+shift.dot(a.cell), dr_direct) abs_dr_from_dr = np.sqrt(np.sum(dr*dr, axis=1)) abs_dr_direct = np.sqrt(np.sum(dr_direct*dr_direct, axis=1)) self.assertTrue(np.all(np.abs(abs_dr-abs_dr_from_dr) < 1e-12)) self.assertTrue(np.all(np.abs(abs_dr-abs_dr_direct) < 1e-12)) self.assertTrue(np.all(np.abs(dr-dr_direct) < 1e-12)) def test_neighbour_list_triangular(self): a = triangular_lattice_slab(1.0, 2, 2) i, j, D, S = neighbour_list('ijDS', a, 1.2) D2 = a.positions[j] - a.positions[i] + S.dot(a.cell) self.assertArrayAlmostEqual(D, D2) def test_small_cell(self): a = ase.Atoms('C', positions=[[0.5, 0.5, 0.5]], cell=[1, 1, 1], pbc=True) i, j, dr, shift = neighbour_list("ijDS", a, 1.1) assert np.bincount(i)[0] == 6 assert (dr == shift).all() i, j = neighbour_list("ij", a, 1.5) assert np.bincount(i)[0] == 18 a.set_pbc(False) i = neighbour_list("i", a, 1.1) assert len(i) == 0 a.set_pbc([True, False, False]) i = neighbour_list("i", a, 1.1) assert np.bincount(i)[0] == 2 a.set_pbc([True, False, True]) i = neighbour_list("i", a, 1.1) assert np.bincount(i)[0] == 4 def test_out_of_cell_small_cell(self): a = ase.Atoms('CC', positions=[[0.5, 0.5, 0.5], [1.1, 0.5, 0.5]], cell=[1, 1, 1], pbc=False) i1, j1, r1 = neighbour_list("ijd", a, 1.1) a.set_cell([2, 1, 1]) i2, j2, r2 = neighbour_list("ijd", a, 1.1) self.assertArrayAlmostEqual(i1, i2) self.assertArrayAlmostEqual(j1, j2) self.assertArrayAlmostEqual(r1, r2) def test_out_of_cell_large_cell(self): a = ase.Atoms('CC', positions=[[9.5, 0.5, 0.5], [10.1, 0.5, 0.5]], cell=[10, 10, 10], pbc=False) i1, j1, r1 = neighbour_list("ijd", a, 1.1) a.set_cell([20, 10, 10]) i2, j2, r2 = neighbour_list("ijd", a, 1.1) self.assertArrayAlmostEqual(i1, i2) self.assertArrayAlmostEqual(j1, j2) self.assertArrayAlmostEqual(r1, r2) def test_hexagonal_cell(self): for sx in range(3): a = ase.lattice.hexagonal.Graphite('C', latticeconstant=(2.5, 10.0), size=[sx+1, sx+1, 1]) i = neighbour_list("i", a, 1.85) self.assertTrue(np.all(np.bincount(i)==3)) def test_first_neighbours(self): i = [1,1,1,1,3,3,3] self.assertArrayAlmostEqual(first_neighbours(5, i), [-1,0,4,4,7,7]) i = [0,1,2,3,4,5] self.assertArrayAlmostEqual(first_neighbours(6, i), [0,1,2,3,4,5,6]) i = [0,1,2,3,5,6] self.assertArrayAlmostEqual(first_neighbours(8, i), [0,1,2,3,4,4,5,6,6]) i = [0,1,2,3,3,5,6] self.assertArrayAlmostEqual(first_neighbours(8, i), [0,1,2,3,5,5,6,7,7]) def test_multiple_elements(self): a = molecule('HCOOH') a.center(vacuum=5.0) io.write('HCOOH.cfg', a) i = neighbour_list("i", a, 1.85) self.assertArrayAlmostEqual(np.bincount(i), [2,3,1,1,1]) cutoffs = {(1, 6): 1.2} i = neighbour_list("i", a, cutoffs) self.assertArrayAlmostEqual(np.bincount(i), [0,1,0,0,1]) cutoffs = {(6, 8): 1.4} i = neighbour_list("i", a, cutoffs) self.assertArrayAlmostEqual(np.bincount(i), [1,2,1]) cutoffs = {('H', 'C'): 1.2, (6, 8): 1.4} i = neighbour_list("i", a, cutoffs) self.assertArrayAlmostEqual(np.bincount(i), [1,3,1,0,1]) def test_noncubic(self): a = bulk("Al", cubic=False) i, j, d = neighbour_list("ijd", a, 3.1) self.assertArrayAlmostEqual(np.bincount(i), [12]) self.assertArrayAlmostEqual(d, [2.86378246]*12) def test_out_of_bounds(self): nat = 10 atoms = ase.Atoms(numbers=range(nat), cell=[(0.2, 1.2, 1.4), (1.4, 0.1, 1.6), (1.3, 2.0, -0.1)]) atoms.set_scaled_positions(3 * np.random.random((nat, 3)) - 1) for p1 in range(2): for p2 in range(2): for p3 in range(2): atoms.set_pbc((p1, p2, p3)) i, j, d, D, S = neighbour_list("ijdDS", atoms, atoms.numbers * 0.2 + 0.5) c = np.bincount(i, minlength=nat) atoms2 = atoms.repeat((p1 + 1, p2 + 1, p3 + 1)) i2, j2, d2, D2, S2 = neighbour_list("ijdDS", atoms2, atoms2.numbers * 0.2 + 0.5) c2 = np.bincount(i2, minlength=nat) c2.shape = (-1, nat) dd = d.sum() * (p1 + 1) * (p2 + 1) * (p3 + 1) - d2.sum() dr = np.linalg.solve(atoms.cell.T, (atoms.positions[1]-atoms.positions[0]).T).T+np.array([0,0,3]) self.assertTrue(abs(dd) < 1e-10) self.assertTrue(not (c2 - c).any()) def test_wrong_number_of_cutoffs(self): nat = 10 atoms = ase.Atoms(numbers=range(nat), cell=[(0.2, 1.2, 1.4), (1.4, 0.1, 1.6), (1.3, 2.0, -0.1)]) atoms.set_scaled_positions(3 * np.random.random((nat, 3)) - 1) exception_thrown = False try: i, j, d, D, S = neighbour_list("ijdDS", atoms, np.ones(len(atoms)-1)) except TypeError: exception_thrown = True self.assertTrue(exception_thrown) def test_shrink_wrapped_direct_call(self): a = io.read('aC.cfg') r = a.positions j, dr, i, abs_dr, shift = neighbour_list("jDidS", positions=r, cutoff=1.85) self.assertTrue((np.bincount(i) == np.bincount(j)).all()) dr_direct = r[j]-r[i] abs_dr_from_dr = np.sqrt(np.sum(dr*dr, axis=1)) abs_dr_direct = np.sqrt(np.sum(dr_direct*dr_direct, axis=1)) self.assertTrue(np.all(np.abs(abs_dr-abs_dr_from_dr) < 1e-12)) self.assertTrue(np.all(np.abs(abs_dr-abs_dr_direct) < 1e-12)) self.assertTrue(np.all(np.abs(dr-dr_direct) < 1e-12)) class TestTriplets(matscipytest.MatSciPyTestCase): def test_get_jump_indicies(self): first_triplets = get_jump_indicies([0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]) first_triplets_comp = [0, 3, 8, 11, 15, 19] assert np.all(first_triplets == first_triplets_comp) first_triplets = get_jump_indicies([0]) first_triplets_comp = [0, 1] # print(first_triplets, first_triplets_comp) assert np.all(first_triplets == first_triplets_comp) def test_triplet_list(self): ij_t_comp = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11] ik_t_comp = [1, 2, 0, 2, 0, 1, 4, 5, 3, 5, 3, 4, 7, 8, 6, 8, 6, 7, 10, 11, 9, 11, 9, 10] i_n = [0]*2+[1]*4+[2]*4 first_i = get_jump_indicies(i_n) ij_t_comp = [0, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9] ik_t_comp = [1, 0, 3, 4, 5, 2, 4, 5, 2, 3, 5, 2, 3, 4, 7, 8, 9, 6, 8, 9, 6, 7, 9, 6, 7, 8] a = triplet_list(first_i) assert np.alltrue(a[0] == ij_t_comp) assert np.alltrue(a[1] == ik_t_comp) first_i = np.array([0, 2, 6, 10], dtype='int32') a = triplet_list(first_i, [2.2]*4+[3.0]*2+[2.0]*4, 2.6) ij_t_comp = [0, 1, 2, 3, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9] ik_t_comp = [1, 0, 3, 2, 7, 8, 9, 6, 8, 9, 6, 7, 9, 6, 7, 8] assert np.all(a[0] == ij_t_comp) assert np.all(a[1] == ik_t_comp) first_i = np.array([0, 2, 6, 10], dtype='int32') a = triplet_list(first_i) ij_t_comp = [0, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9] ik_t_comp = [1, 0, 3, 4, 5, 2, 4, 5, 2, 3, 5, 2, 3, 4, 7, 8, 9, 6, 8, 9, 6, 7, 9, 6, 7, 8] assert np.all(a[0] == ij_t_comp) assert np.all(a[1] == ik_t_comp) def test_triplet_list_with_cutoff(self): first_i = np.array([0, 2, 6, 10], dtype='int32') a = triplet_list(first_i, [2.2]*9+[3.0], 2.6) ij_t_comp = [0, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8] ik_t_comp = [1, 0, 3, 4, 5, 2, 4, 5, 2, 3, 5, 2, 3, 4, 7, 8, 6, 8, 6, 7] assert np.all(a[0] == ij_t_comp) assert np.all(a[1] == ik_t_comp) first_i = np.array([0, 2, 6, 10], dtype='int32') a = triplet_list(first_i, [2.2]*4+[3.0]*2+[2.0]*4, 2.6) ij_t_comp = [0, 1, 2, 3, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9] ik_t_comp = [1, 0, 3, 2, 7, 8, 9, 6, 8, 9, 6, 7, 9, 6, 7, 8] assert np.all(a[0] == ij_t_comp) assert np.all(a[1] == ik_t_comp) class TestNeighbourhood(matscipytest.MatSciPyTestCase): theta0 = np.pi / 3 atoms = ase.Atoms("H2O", positions=[[-1, 0, 0], [0, 0, 0], [np.cos(theta0), np.sin(theta0), 0]], cell=ase.cell.Cell.fromcellpar([10, 10, 10, 90, 90, 90])) molecules = Molecules(bonds_connectivity=[[0, 1], [2, 1], [0, 2]], bonds_types=[1, 2, 3], angles_connectivity=[ [0, 1, 2], [2, 0, 1], [1, 0, 2], ], angles_types=[1, 2, 3]) cutoff = CutoffNeighbourhood(cutoff=10.) molecule = MolecularNeighbourhood(molecules) def test_pairs(self): cutoff_d = self.cutoff.get_pairs(self.atoms, "ijdD") molecule_d = self.molecule.get_pairs(self.atoms, "ijdD") mask_extra_bonds = self.molecule.connectivity["bonds"]["type"] >= 0 # Lexicographic sort of pair indices, as in cutoff neighborhood p = CutoffNeighbourhood.lexsort( np.asarray(molecule_d[0:2]).T[mask_extra_bonds] ) # print("CUTOFF", cutoff_d) # print("MOLECULE", molecule_d) for c, m in zip(cutoff_d, molecule_d): print("c =", c) print("m =", m[mask_extra_bonds][p]) self.assertArrayAlmostEqual(c, m[mask_extra_bonds][p], tol=1e-10) def test_triplets(self): cutoff_pairs = np.array(self.cutoff.get_pairs(self.atoms, "ij")).T molecules_pairs = np.array(self.molecule.get_pairs(self.atoms, "ij")).T cutoff_d = self.cutoff.get_triplets(self.atoms, "ijk") molecule_d = self.molecule.get_triplets(self.atoms, "ijk") # We compare: # - i_p[ij_t], j_p[ij_t] # - i_p[ik_t], j_p[ik_t] # - i_p[jk_t], j_p[jk_t] sort_cutoff, sort_molecules = [], [] for c, m in zip(cutoff_d, molecule_d): sort_cutoff.append(CutoffNeighbourhood.lexsort(cutoff_pairs[c])) sort_molecules.append(CutoffNeighbourhood.lexsort(molecules_pairs[m])) cpairs = cutoff_pairs[c][sort_cutoff[-1]] mpairs = molecules_pairs[m][sort_molecules[-1]] print("c =", cpairs) print("m =", mpairs) self.assertArrayAlmostEqual(cpairs[:, 0], mpairs[:, 0], tol=1e-10) self.assertArrayAlmostEqual(cpairs[:, 1], mpairs[:, 1], tol=1e-10) # Testing computed distances and vectors cutoff_d = self.cutoff.get_triplets(self.atoms, "dD") molecule_d = self.molecule.get_triplets(self.atoms, "dD") for c, m, pc, pm in zip(cutoff_d, molecule_d, sort_cutoff, sort_molecules): self.assertArrayAlmostEqual(c[pc], m[pm], tol=1e-10) def test_pair_types(self): pass if __name__ == '__main__': unittest.main()
15,906
38.967337
117
py
matscipy
matscipy-master/tests/test_bulk_properties.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2021 Jan Griesser (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import pytest import numpy as np import ase.constraints from ase.lattice.compounds import B1, B2, B3 from ase.lattice.cubic import BodyCenteredCubic, Diamond, FaceCenteredCubic from ase.optimize import FIRE from ase.units import GPa import matscipy.calculators.manybody.explicit_forms.stillinger_weber as stillinger_weber import matscipy.calculators.manybody.explicit_forms.kumagai as kumagai import matscipy.calculators.manybody.explicit_forms.tersoff_brenner as tersoff_brenner from matscipy.calculators.manybody import Manybody from matscipy.calculators.manybody.explicit_forms import Kumagai, TersoffBrenner, StillingerWeber from matscipy.elasticity import full_3x3x3x3_to_Voigt_6x6 ### sx = 1 tests = [ ("Kumagai-dia-Si", Kumagai(kumagai.Kumagai_Comp_Mat_Sci_39_Si), Diamond("Si", size=[sx, sx, sx]), dict(Ec=4.630, a0=5.429, C11=166.4, C12=65.3, C44=77.1, C440=120.9)), ("StillingerWeber-dia-Si", StillingerWeber(stillinger_weber.Stillinger_Weber_PRB_31_5262_Si), Diamond("Si", size=[sx, sx, sx]), dict(Ec=4.3363, a0=5.431, C11=161.6, C12=81.6, C44=60.3, C440=117.2, B=108.3)), ("Tersoff3-dia-C", TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), Diamond("C", size=[sx, sx, sx]), dict(Ec=7.396 - 0.0250, a0=3.566, C11=1067, C12=104, C44=636, C440=671)), ("Tersoff3-dia-Si", TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), Diamond("Si", size=[sx, sx, sx]), dict(Ec=4.63, a0=5.432, C11=143, C12=75, C44=69, C440=119, B=98)), ("Tersoff3-dia-Si-C", TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), B3(["Si", "C"], latticeconstant=4.3596, size=[sx, sx, sx]), dict(Ec=6.165, a0=4.321, C11=437, C12=118, C440=311, B=224)), ("MatsunagaFisherMatsubara-dia-C", TersoffBrenner(tersoff_brenner.Matsunaga_Fisher_Matsubara_Jpn_J_Appl_Phys_39_48_B_C_N), Diamond("C", size=[sx, sx, sx]), dict(Ec=7.396 - 0.0250, a0=3.566, C11=1067, C12=104, C44=636, C440=671)), ("MatsunagaFisherMatsubara-dia-B-N", TersoffBrenner(tersoff_brenner.Matsunaga_Fisher_Matsubara_Jpn_J_Appl_Phys_39_48_B_C_N), B3(["B", "N"], latticeconstant=3.7, size=[sx, sx, sx]), dict(Ec=6.63, a0=3.658, B=385)), ("BrennerI-dia-C", TersoffBrenner(tersoff_brenner.Brenner_PRB_42_9458_C_I), Diamond("C", size=[sx, sx, sx]), {}), ("BrennerII-dia-C", TersoffBrenner(tersoff_brenner.Brenner_PRB_42_9458_C_II), Diamond("C", size=[sx, sx, sx]), dict(Ec=7.376 - 0.0524, a0=3.558, C11=621, C12=415, C44=383, B=484)), ("ErhartAlbeSiC-dia-C", TersoffBrenner(tersoff_brenner.Erhart_PRB_71_035211_SiC), Diamond("C", size=[sx, sx, sx]), dict(Ec=7.3731, a0=3.566, C11=1082, C12=127, C44=673, B=445)), ("ErhartAlbeSiC-dia-Si", TersoffBrenner(tersoff_brenner.Erhart_PRB_71_035211_SiC), Diamond("Si", size=[sx, sx, sx]), dict(Ec=4.63, a0=5.429, C11=167, C12=65, C44=60 ,C440=105, B=99)), ("ErhartAlbeSiC-dia-SiII", TersoffBrenner(tersoff_brenner.Erhart_PRB_71_035211_Si), Diamond("Si", size=[sx, sx, sx]), dict(Ec=4.63, a0=5.429, C11=167, C12=65, C44=72, C440=111, B=99)), ("ErhartAlbeSiC-dia-Si-C", TersoffBrenner(tersoff_brenner.Erhart_PRB_71_035211_SiC), B3(["Si", "C"], latticeconstant=4.3596, size=[sx, sx, sx]), dict(Ec=6.340, a0=4.359, C11=382, C12=145, C440=305, B=224)), # FIXME! These potential don't work yet. # ("AlbeNordlundAverbackPtC-fcc-Pt", # TersoffBrenner(tersoff_brenner.Albe_PRB_65_195124_PtC), # FaceCenteredCubic("Pt", size=[sx, sx, sx]), # dict(Ec=5.77, a0=3.917, C11=351.5, C12=248.1, C44=89.5, B=282.6)), # ("AlbeNordlundAverbackPtC-bcc-Pt", # TersoffBrenner(tersoff_brenner.Albe_PRB_65_195124_PtC), # BodyCenteredCubic("Pt", latticeconstant=3.1, size=[sx, sx, sx]), # dict(Ec=5.276, a0=3.094, B=245.5)), # ("AlbeNordlundAverbackPtC-B1-PtC", # TersoffBrenner(tersoff_brenner.Albe_PRB_65_195124_PtC), # B1(["Pt", "C"], latticeconstant=4.5, size=[sx, sx, sx]), # dict(Ec=10.271, a0=4.476, B=274)), # ("AlbeNordlundAverbackPtC-B2-PtC", # TersoffBrenner(tersoff_brenner.Albe_PRB_65_195124_PtC), # B2(["Pt", "C"], latticeconstant=2.7, size=[sx, sx, sx]), # dict(Ec=9.27, a0=2.742, B=291)), ] @pytest.mark.parametrize('test', tests) def test_cubic_elastic_constants(test): name, pot, atoms, mat = test calculator = Manybody(**pot) atoms.translate([0.1, 0.1, 0.1]) atoms.set_scaled_positions(atoms.get_scaled_positions()) atoms.calc = calculator c1, c2, c3 = atoms.get_cell() a0 = np.sqrt(np.dot(c1, c1)) / sx FIRE(ase.constraints.StrainFilter(atoms, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.0001) # Ec Ec = -atoms.get_potential_energy() / len(atoms) # a0 c1, c2, c3 = atoms.get_cell() a0 = np.sqrt(np.dot(c1, c1)) / sx # C11, C12, C44 Caffine = calculator.get_birch_coefficients(atoms) Cnonaffine = calculator.get_non_affine_contribution_to_elastic_constants(atoms) C = full_3x3x3x3_to_Voigt_6x6(Caffine + Cnonaffine) C11 = C[0, 0] / GPa C12 = C[0, 1] / GPa C44 = C[3, 3] / GPa C110 = full_3x3x3x3_to_Voigt_6x6(Caffine)[0, 0] / GPa C120 = full_3x3x3x3_to_Voigt_6x6(Caffine)[0, 1] / GPa C440 = full_3x3x3x3_to_Voigt_6x6(Caffine)[3, 3] / GPa B = (C11 + 2 * C12) / 3 # print to screen print() print(f'=== {name}===') l1 = f' ' l2 = f'Computed: ' l3 = f'Reference:' for prop in ['Ec', 'a0', 'C11', 'C110', 'C12', 'C120', 'C44', 'C440', 'B']: l1 += prop.rjust(11) l2 += f'{locals()[prop]:.2f}'.rjust(11) if prop in mat: l3 += f'{float(mat[prop]):.2f}'.rjust(11) else: l3 += '---'.rjust(11) print(l1) print(l2) print(l3) # actually test properties for prop, value in mat.items(): if prop != 'struct': np.testing.assert_allclose(locals()[prop], value, rtol=0.1)
6,833
39.2
101
py
matscipy
matscipy-master/tests/test_bop.py
# # Copyright 2020-2021 Lars Pastewka (U. Freiburg) # 2021 Jan Griesser (U. Freiburg) # 2020-2021 Jonas Oldenstaedt (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import numpy as np import pytest import ase import ase.constraints from ase import Atoms from ase.optimize import FIRE from ase.lattice.compounds import B3 from ase.lattice.cubic import Diamond import matscipy.calculators.manybody.explicit_forms.stillinger_weber \ as stillinger_weber import matscipy.calculators.manybody.explicit_forms.kumagai as kumagai import matscipy.calculators.manybody.explicit_forms.tersoff_brenner \ as tersoff_brenner from matscipy.calculators.manybody import Manybody from matscipy.calculators.manybody.explicit_forms import ( Kumagai, TersoffBrenner, StillingerWeber, ) from matscipy.numerical import ( numerical_hessian, numerical_forces, numerical_stress, numerical_nonaffine_forces, ) from matscipy.elasticity import ( fit_elastic_constants, measure_triclinic_elastic_constants, ) @pytest.mark.parametrize('a0', [5.2, 5.3, 5.4, 5.5]) @pytest.mark.parametrize('par', [ Kumagai(kumagai.Kumagai_Comp_Mat_Sci_39_Si), TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), StillingerWeber(stillinger_weber.Stillinger_Weber_PRB_31_5262_Si) ]) def test_stress(a0, par): atoms = Diamond('Si', size=[1, 1, 1], latticeconstant=a0) calculator = Manybody(**par) atoms.calc = calculator s = atoms.get_stress() sn = numerical_stress(atoms, d=0.0001) np.testing.assert_allclose(s, sn, atol=1e-6) def test_hessian_divide_by_masses(): # Test the computation of dynamical matrix atoms = ase.io.read('aSi.cfg') masses_n = np.random.randint(1, 10, size=len(atoms)) atoms.set_masses(masses=masses_n) kumagai_potential = kumagai.Kumagai_Comp_Mat_Sci_39_Si calc = Manybody(**Kumagai(kumagai_potential)) D_ana = calc.get_hessian(atoms, divide_by_masses=True).todense() H_ana = calc.get_hessian(atoms).todense() masses_nc = masses_n.repeat(3) H_ana /= np.sqrt(masses_nc.reshape(-1, 1) * masses_nc.reshape(1, -1)) np.testing.assert_allclose(D_ana, H_ana, atol=1e-4) @pytest.mark.parametrize('d', np.arange(1.0, 2.3, 0.15)) @pytest.mark.parametrize('par', [ Kumagai(kumagai.Kumagai_Comp_Mat_Sci_39_Si), TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), StillingerWeber(stillinger_weber.Stillinger_Weber_PRB_31_5262_Si) ]) def test_small1(d, par): # Test forces and hessian matrix for Kumagai small = Atoms( [14] * 4, [(d, 0, d / 2), (0, 0, 0), (d, 0, 0), (0, 0, d)], cell=(100, 100, 100)) small.center(vacuum=10.0) compute_forces_and_hessian(small, par) @pytest.mark.parametrize('d', np.arange(1.0, 2.3, 0.15)) @pytest.mark.parametrize('par', [ Kumagai(kumagai.Kumagai_Comp_Mat_Sci_39_Si), TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), StillingerWeber(stillinger_weber.Stillinger_Weber_PRB_31_5262_Si) ]) def test_small2(d, par): # Test forces and hessian matrix for Kumagai small2 = Atoms( [14] * 5, [(d, 0, d / 2), (0, 0, 0), (d, 0, 0), (0, 0, d), (0, d, d)], cell=(100, 100, 100)) small2.center(vacuum=10.0) compute_forces_and_hessian(small2, par) @pytest.mark.parametrize('a0', [5.2, 5.3, 5.4, 5.5]) @pytest.mark.parametrize('par', [ Kumagai(kumagai.Kumagai_Comp_Mat_Sci_39_Si), TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), StillingerWeber(stillinger_weber.Stillinger_Weber_PRB_31_5262_Si) ]) def test_crystal_forces_and_hessian(a0, par): # Test forces, hessian, non-affine forces and elastic constants for a Si crystal Si_crystal = Diamond('Si', size=[1, 1, 1], latticeconstant=a0) compute_forces_and_hessian(Si_crystal, par) @pytest.mark.parametrize('a0', [5.0, 5.2, 5.3, 5.4, 5.5]) @pytest.mark.parametrize('par', [ Kumagai(kumagai.Kumagai_Comp_Mat_Sci_39_Si), TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), StillingerWeber(stillinger_weber.Stillinger_Weber_PRB_31_5262_Si) ]) def test_crystal_elastic_constants(a0, par): # Test forces, hessian, non-affine forces and elastic constants for a Si crystal Si_crystal = Diamond('Si', size=[1, 1, 1], latticeconstant=a0) compute_elastic_constants(Si_crystal, par) @pytest.mark.parametrize('par', [ Kumagai(kumagai.Kumagai_Comp_Mat_Sci_39_Si), TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), StillingerWeber(stillinger_weber.Stillinger_Weber_PRB_31_5262_Si) ]) def test_amorphous(par): # Tests for amorphous Si aSi = ase.io.read('aSi_N8.xyz') aSi.calc = Manybody(**par) # Non-zero forces and Hessian compute_forces_and_hessian(aSi, par) # Test forces, hessian, non-affine forces and elastic constants for a stress-free amorphous Si configuration FIRE( ase.constraints.UnitCellFilter( aSi, mask=[1, 1, 1, 1, 1, 1], hydrostatic_strain=False), logfile=None).run(fmax=1e-5) compute_forces_and_hessian(aSi, par) compute_elastic_constants(aSi, par) @pytest.mark.parametrize('a0', [4.3, 4.4, 4.5]) @pytest.mark.parametrize('par', [ TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), TersoffBrenner(tersoff_brenner.Erhart_PRB_71_035211_SiC) ]) def test_tersoff_multicomponent_crystal_forces_and_hessian(a0, par): # Test forces, hessian, non-affine forces and elastic constants for a Si-C crystal Si_crystal = B3(['Si', 'C'], size=[1, 1, 1], latticeconstant=a0) compute_forces_and_hessian(Si_crystal, par) @pytest.mark.parametrize('a0', [4.3, 4.4, 4.5]) @pytest.mark.parametrize('par', [ TersoffBrenner(tersoff_brenner.Tersoff_PRB_39_5566_Si_C), TersoffBrenner(tersoff_brenner.Erhart_PRB_71_035211_SiC) ]) def test_tersoff_multicomponent_crystal_elastic_constants(a0, par): # Test forces, hessian, non-affine forces and elastic constants for a Si-C crystal Si_crystal = B3(['Si', 'C'], size=[1, 1, 1], latticeconstant=a0) compute_elastic_constants(Si_crystal, par) # 0 - Tests Hessian term #4 (with all other terms turned off) def term4(test_cutoff): return { 'atom_type': lambda n: np.zeros_like(n), 'pair_type': lambda i, j: np.zeros_like(i), 'F': lambda x, y, i, p: x, 'G': lambda x, y, i, ij, ik: np.ones_like(x[:, 0]), 'd1F': lambda x, y, i, p: np.ones_like(x), 'd11F': lambda x, y, i, p: np.zeros_like(x), 'd2F': lambda x, y, i, p: np.zeros_like(y), 'd22F': lambda x, y, i, p: np.zeros_like(y), 'd12F': lambda x, y, i, p: np.zeros_like(y), 'd1G': lambda x, y, i, ij, ik: np.zeros_like(y), 'd2G': lambda x, y, i, ij, ik: np.zeros_like(y), 'd11G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), # if beta <= 1 else beta*(beta-1)*x.**(beta-2) * y[:, 2]**gamma, 'd12G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), 'd22G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), 'cutoff': test_cutoff } # 1 - Tests Hessian term #1 (and #4, with all other terms turned off) def term1(test_cutoff): return { 'atom_type': lambda n: np.zeros_like(n), 'pair_type': lambda i, j: np.zeros_like(i), 'F': lambda x, y, i, p: x**2, 'G': lambda x, y, i, ij, ik: np.ones_like(x[:, 0]), 'd1F': lambda x, y, i, p: 2 * x, 'd11F': lambda x, y, i, p: 2 * np.ones_like(x), 'd2F': lambda x, y, i, p: np.zeros_like(y), 'd22F': lambda x, y, i, p: np.zeros_like(y), 'd12F': lambda x, y, i, p: np.zeros_like(y), 'd1G': lambda x, y, i, ij, ik: np.zeros_like(x), 'd2G': lambda x, y, i, ij, ik: np.zeros_like(y), 'd11G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), 'd12G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), 'd22G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), 'cutoff': test_cutoff } # 2 - Tests D_11 parts of Hessian term #5 def d11_term5(test_cutoff): return { 'atom_type': lambda n: np.zeros_like(n), 'pair_type': lambda i, j: np.zeros_like(i), 'F': lambda x, y, i, p: y, 'G': lambda x, y, i, ij, ik: np.sum(x**2, axis=1), 'd1F': lambda x, y, i, p: np.zeros_like(x), 'd11F': lambda x, y, i, p: np.zeros_like(x), 'd2F': lambda x, y, i, p: np.ones_like(x), 'd22F': lambda x, y, i, p: np.zeros_like(x), 'd12F': lambda x, y, i, p: np.zeros_like(x), 'd1G': lambda x, y, i, ij, ik: 2 * x, 'd2G': lambda x, y, i, ij, ik: np.zeros_like(y), 'd11G': lambda x, y, i, ij, ik: np.array([2 * np.eye(3)] * x.shape[0]), # np.ones_like(x).reshape(-1,3,1)*np.ones_like(y).reshape(-1,1,3), #if beta <= 1 else beta*(beta-1)*x.**(beta-2) * y[:, 2]**gamma, 'd12G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), 'd22G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), 'cutoff': test_cutoff } # 3 - Tests D_22 parts of Hessian term #5 def d22_term5(test_cutoff): return { 'atom_type': lambda n: np.zeros_like(n), 'pair_type': lambda i, j: np.zeros_like(i), 'F': lambda x, y, i, p: y, 'G': lambda x, y, i, ij, ik: np.sum(y**2, axis=1), 'd1F': lambda x, y, i, p: np.zeros_like(x), 'd11F': lambda x, y, i, p: np.zeros_like(x), 'd2F': lambda x, y, i, p: np.ones_like(x), 'd22F': lambda x, y, i, p: np.zeros_like(x), 'd12F': lambda x, y, i, p: np.zeros_like(x), 'd2G': lambda x, y, i, ij, ik: 2 * y, 'd1G': lambda x, y, i, ij, ik: np.zeros_like(x), 'd22G': lambda x, y, i, ij, ik: np.array([2 * np.eye(3)] * x.shape[0]), # np.ones_like(x).reshape(-1,3,1)*np.ones_like(y).reshape(-1,1,3), #if beta <= 1 else beta*(beta-1)*x.**(beta-2) * y[:, 2]**gamma, 'd12G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), 'd11G': lambda x, y, i, ij, ik: 0 * x.reshape(-1, 3, 1) * y.reshape(-1, 1, 3), 'cutoff': test_cutoff } @pytest.mark.parametrize('term', [term1, term4, d11_term5, d22_term5]) @pytest.mark.parametrize('test_cutoff', [3.0]) def test_generic_potential_form1(test_cutoff, term): d = 2.0 # Si2 bondlength small = Atoms( [14] * 4, [(d, 0, d / 2), (0, 0, 0), (d, 0, 0), (0, 0, d)], cell=(100, 100, 100)) small.center(vacuum=10.0) compute_forces_and_hessian(small, term(test_cutoff)) @pytest.mark.parametrize('term', [term1, term4, d11_term5, d22_term5]) @pytest.mark.parametrize('test_cutoff', [3.5]) def test_generic_potential_form2(test_cutoff, term): d = 2.0 # Si2 bondlength small2 = Atoms( [14] * 5, [(d, 0, d / 2), (0, 0, 0), (d, 0, 0), (0, 0, d), (0, d, d)], cell=(100, 100, 100)) small2.center(vacuum=10.0) compute_forces_and_hessian(small2, term(test_cutoff)) def compute_forces_and_hessian(a, par): # function to test the bop AbellTersoffBrenner class on # a potential given by the form defined in par # Parameters # ---------- # a : ase atoms object # passes an atomic configuration as an ase atoms object # par : bop explicit form # defines the explicit form of the bond order potential calculator = Manybody(**par) a.calc = calculator # Forces ana_forces = a.get_forces() num_forces = numerical_forces(a, d=1e-5) # print('num\n', num_forces) # print('ana\n', ana_forces) np.testing.assert_allclose(ana_forces, num_forces, atol=1e-3) # Hessian ana_hessian = np.array(calculator.get_hessian(a).todense()) num_hessian = np.array( numerical_hessian(a, d=1e-5, indices=None).todense()) # print('ana\n', ana_hessian) # print('num\n', num_hessian) # print('ana - num\n', (np.abs(ana_hessian - num_hessian) > 1e-6).astype(int)) np.testing.assert_allclose(ana_hessian, ana_hessian.T, atol=1e-6) np.testing.assert_allclose(ana_hessian, num_hessian, atol=1e-4) ana2_hessian = calculator.get_hessian_from_second_derivative(a) np.testing.assert_allclose(ana2_hessian, ana2_hessian.T, atol=1e-6) np.testing.assert_allclose(ana_hessian, ana2_hessian, atol=1e-5) def compute_elastic_constants(a, par): # function to test the bop AbellTersoffBrenner class on # a potential given by the form defined in par # Parameters # ---------- # a : ase atoms object # passes an atomic configuration as an ase atoms object # par : bop explicit form # defines the explicit form of the bond order potential calculator = Manybody(**par) a.calc = calculator # Non-affine forces num_naF = numerical_nonaffine_forces(a, d=1e-5) ana_naF1 = calculator.get_non_affine_forces_from_second_derivative(a) ana_naF2 = calculator.get_property('nonaffine_forces', a) # print("num_naF[0]: \n", num_naF[0]) # print("ana_naF1[0]: \n", ana_naF1[0]) # print("ana_naF2[0]: \n", ana_naF2[0]) np.testing.assert_allclose(ana_naF1, num_naF, atol=0.01) np.testing.assert_allclose(ana_naF1, ana_naF2, atol=1e-4) # Birch elastic constants C_ana = a.calc.get_property('birch_coefficients', a) C_num = measure_triclinic_elastic_constants(a, delta=1e-3) np.testing.assert_allclose(C_ana, C_num, atol=.3) # Non-affine elastic constants C_ana = a.calc.get_property('elastic_constants', a) C_num = measure_triclinic_elastic_constants( a, optimizer=FIRE, fmax=1e-6, delta=1e-3, ) np.testing.assert_allclose(C_ana, C_num, atol=.3)
14,906
34.408551
138
py
matscipy
matscipy-master/tests/test_supercell_calculator.py
# # Copyright 2014-2015, 2017, 2020-2021 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014-2017) James Kermode, Warwick University # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest from ase.build import bulk import matscipytest from matscipy.calculators import EAM, SupercellCalculator ### class TestSupercellCalculator(matscipytest.MatSciPyTestCase): def test_eam(self): for calc in [EAM('Au-Grochola-JCP05.eam.alloy')]: a = bulk('Au') a *= (2, 2, 2) a.rattle(0.1) a.calc = calc e = a.get_potential_energy() f = a.get_forces() s = a.get_stress() a.set_calculator(SupercellCalculator(calc, (3, 3, 3))) self.assertAlmostEqual(e, a.get_potential_energy()) self.assertArrayAlmostEqual(f, a.get_forces()) self.assertArrayAlmostEqual(s, a.get_stress()) ### if __name__ == '__main__': unittest.main()
2,641
35.191781
72
py
matscipy
matscipy-master/tests/test_rotation_of_elastic_constants.py
# # Copyright 2014-2015, 2020-2021 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np from ase.constraints import StrainFilter from ase.lattice.cubic import Diamond, FaceCenteredCubic from ase.optimize import FIRE from ase.units import GPa import matscipytest from matscipy.calculators.eam import EAM from matscipy.elasticity import (CubicElasticModuli, Voigt_6x6_to_cubic, cubic_to_Voigt_6x6, full_3x3x3x3_to_Voigt_6x6, measure_triclinic_elastic_constants, rotate_cubic_elastic_constants, rotate_elastic_constants) ### class TestCubicElasticModuli(matscipytest.MatSciPyTestCase): fmax = 1e-6 delta = 1e-6 def test_rotation(self): for make_atoms, calc in [ # ( lambda a0,x : # FaceCenteredCubic('He', size=[1,1,1], # latticeconstant=3.5 if a0 is None else a0, # directions=x), # LJCut(epsilon=10.2, sigma=2.28, cutoff=5.0, shift=True) ), ( lambda a0,x : FaceCenteredCubic('Au', size=[1,1,1], latticeconstant=a0, directions=x), EAM('Au-Grochola-JCP05.eam.alloy') ), # ( lambda a0,x : Diamond('Si', size=[1,1,1], latticeconstant=a0, # directions=x), # Kumagai() ) #( lambda a0,x : FaceCenteredCubic('Au', size=[1,1,1], # latticeconstant=a0, directions=x), # EAM(potential='Au-Grochola-JCP05.eam.alloy') ), ]: a = make_atoms(None, [[1,0,0], [0,1,0], [0,0,1]]) a.set_calculator(calc) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=self.fmax) latticeconstant = np.mean(a.cell.diagonal()) C6 = measure_triclinic_elastic_constants(a, delta=self.delta, fmax=self.fmax) C11, C12, C44 = Voigt_6x6_to_cubic(full_3x3x3x3_to_Voigt_6x6(C6)) / GPa el = CubicElasticModuli(C11, C12, C44) C_m = full_3x3x3x3_to_Voigt_6x6(measure_triclinic_elastic_constants( a, delta=self.delta, fmax=self.fmax)) / GPa self.assertArrayAlmostEqual(el.stiffness(), C_m, tol=0.01) for directions in [ [[1,0,0], [0,1,0], [0,0,1]], [[0,1,0], [0,0,1], [1,0,0]], [[1,1,0], [0,0,1], [1,-1,0]], [[1,1,1], [-1,-1,2], [1,-1,0]] ]: a, b, c = directions a = make_atoms(latticeconstant, directions) a.set_calculator(calc) directions = np.array([ np.array(x)/np.linalg.norm(x) for x in directions ]) C = el.rotate(directions) C_check = el._rotate_explicit(directions) C_check2 = rotate_cubic_elastic_constants(C11, C12, C44, directions) C_check3 = \ rotate_elastic_constants(cubic_to_Voigt_6x6(C11, C12, C44), directions) self.assertArrayAlmostEqual(C, C_check, tol=1e-6) self.assertArrayAlmostEqual(C, C_check2, tol=1e-6) self.assertArrayAlmostEqual(C, C_check3, tol=1e-6) C_m = full_3x3x3x3_to_Voigt_6x6( measure_triclinic_elastic_constants(a, delta=self.delta, fmax=self.fmax)) / GPa self.assertArrayAlmostEqual(C, C_m, tol=1e-2) ### if __name__ == '__main__': unittest.main()
5,508
41.376923
99
py
matscipy
matscipy-master/tests/test_eam_average_atom.py
# # Copyright 2020-2021 Lars Pastewka (U. Freiburg) # 2020 Wolfram G. Nöhring (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # Adrien Gola, Karlsruhe Institute of Technology # Wolfram Nöhring, University of Freiburg # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import os from matscipy.calculators.eam import io, average_atom import matscipytest ### class TestEAMAverageAtom(matscipytest.MatSciPyTestCase): tol = 1e-6 def test_average_atom_Ni_Al(self): """Create A-atom potential for a Ni-Al eam/alloy potential and 15% Al The input potential is from Ref. [1]_ and was downloaded from the NIST database [2]_. The generated The generated A-atom potential is compared to a reference A-atom potential, which was created with an independent implementation. This is not a very strong test, but should capture some regressions. References ---------- [1] G.P. Purja Pun, and Y. Mishin (2009), "Development of an interatomic potential for the Ni-Al system", Philosophical Magazine, 89(34-36), 3245-3267. DOI: 10.1080/14786430903258184. [2] https://www.ctcms.nist.gov/potentials/Download/2009--Purja-Pun-G-P-Mishin-Y--Ni-Al/2/Mishin-Ni-Al-2009.eam.alloy """ input_table = "Mishin-Ni-Al-2009.eam.alloy" reference_table = "Mishin-Ni-Al-2009_reference_A-atom_Ni85Al15.eam.alloy" concentrations = np.array((0.85, 0.15)) source, parameters, F, f, rep = io.read_eam(input_table) (new_parameters, new_F, new_f, new_rep) = average_atom.average_potential( concentrations, parameters, F, f, rep ) ref_source, ref_parameters, ref_F, ref_f, ref_rep = io.read_eam(reference_table) diff_F = np.linalg.norm(ref_F - new_F) diff_f = np.linalg.norm(ref_f - new_f) diff_rep = np.linalg.norm(ref_rep - new_rep) print(diff_F, diff_f, diff_rep) self.assertTrue(diff_F < self.tol) self.assertTrue(diff_f < self.tol) self.assertTrue(diff_rep < self.tol) def test_average_atom_Fe_Cu_Ni(self): """Create A-atom potential for a Fe-Cu-Ni eam/alloy potential at equicomposition The input potential is from Ref. [1]_ and was downloaded from the NIST database [2]_. The generated The generated A-atom potential is compared to a reference A-atom potential, which was created with an independent implementation. This is not a very strong test, but should capture some regressions. References ---------- [1] G. Bonny, R.C. Pasianot, N. Castin, and L. Malerba (2009), "Ternary Fe-Cu-Ni many-body potential to model reactor pressure vessel steels: First validation by simulated thermal annealing", Philosophical Magazine, 89(34-36), 3531-3546. DOI: 10.1080/14786430903299824. [2] https://www.ctcms.nist.gov/potentials/Download/2009--Bonny-G-Pasianot-R-C-Castin-N-Malerba-L--Fe-Cu-Ni/1/FeCuNi.eam.alloy """ input_table = "FeCuNi.eam.alloy" reference_table = "FeCuNi_reference_A-atom_Fe33Cu33Ni33.eam.alloy" concentrations = np.array((1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0)) source, parameters, F, f, rep = io.read_eam(input_table) (new_parameters, new_F, new_f, new_rep) = average_atom.average_potential( concentrations, parameters, F, f, rep ) ref_source, ref_parameters, ref_F, ref_f, ref_rep = io.read_eam(reference_table) diff_F = np.linalg.norm(ref_F - new_F) diff_f = np.linalg.norm(ref_f - new_f) diff_rep = np.linalg.norm(ref_rep - new_rep) print(diff_F, diff_f, diff_rep) self.assertTrue(diff_F < self.tol) self.assertTrue(diff_f < self.tol) self.assertTrue(diff_rep < self.tol) ### if __name__ == '__main__': unittest.main()
5,653
41.511278
133
py
matscipy
matscipy-master/tests/test_angle_distribution.py
# # Copyright 2015, 2020-2021 Lars Pastewka (U. Freiburg) # 2017 Thomas Reichenbach (Fraunhofer IWM) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import ase import ase.io as io import ase.lattice.hexagonal import matscipytest from matscipy.neighbours import neighbour_list from matscipy.angle_distribution import angle_distribution ### class TestAngleDistribution(matscipytest.MatSciPyTestCase): def test_no_angle(self): a = ase.Atoms('CC', positions=[[0.5, 0.5, 0.5], [0.5, 0.5, 1.0]], cell=[2, 2, 2], pbc=True) i, j, dr = neighbour_list("ijD", a, 1.1) hist = angle_distribution(i, j, dr, 20, 1.1) self.assertEqual(hist.sum(), 0) def test_single_angle(self): a = ase.Atoms('CCC', positions=[[0.5, 0.5, 0.5], [0.5, 0.5, 1.0], [0.5, 1.0, 1.0]], cell=[2, 2, 2], pbc=True) i, j, dr = neighbour_list("ijD", a, 0.6) hist = angle_distribution(i, j, dr, 20, 0.6) # v 45 degrees self.assertArrayAlmostEqual(hist, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # ^ 90 degrees def test_single_angle_reversed_order(self): a = ase.Atoms('CCC', positions=[[0.5, 0.5, 0.5], [0.5, 1.0, 1.0], [0.5, 0.5, 1.0]], cell=[2, 2, 2], pbc=True) i, j, dr = neighbour_list("ijD", a, 0.6) hist = angle_distribution(i, j, dr, 20, 0.6) # v 45 degrees self.assertArrayAlmostEqual(hist, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # ^ 90 degrees def test_three_angles(self): a = ase.Atoms('CCC', positions=[[0.5, 0.5, 0.5], [0.5, 0.5, 1.0], [0.5, 1.0, 1.0]], cell=[2, 2, 2], pbc=True) i, j, dr = neighbour_list("ijD", a, 1.1) hist = angle_distribution(i, j, dr, 20) # v 45 degrees self.assertArrayAlmostEqual(hist, [0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # ^ 90 degrees ### if __name__ == '__main__': unittest.main()
4,261
39.980769
73
py
matscipy
matscipy-master/tests/matscipytest.py
# # Copyright 2015, 2017, 2021 Lars Pastewka (U. Freiburg) # 2020 Johannes Hoermann (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import logging from io import StringIO import numpy as np def string_to_array(s): return np.loadtxt(StringIO(s)).T class MatSciPyTestCase(unittest.TestCase): """ Subclass of unittest.TestCase with extra methods for comparing arrays and dictionaries """ def assertDictionariesEqual(self, d1, d2, skip_keys=[], ignore_case=True): def lower_if_ignore_case(k): if ignore_case: return k.lower() else: return k d1 = dict([(lower_if_ignore_case(k),v) for (k,v) in d1.items() if k not in skip_keys]) d2 = dict([(lower_if_ignore_case(k),v) for (k,v) in d2.items() if k not in skip_keys]) if sorted(d1.keys()) != sorted(d2.keys()): self.fail('Dictionaries differ: d1.keys() (%r) != d2.keys() (%r)' % (d1.keys(), d2.keys())) for key in d1: v1, v2 = d1[key], d2[key] if isinstance(v1, list) or isinstance(v1, np.ndarray): try: self.assertArrayAlmostEqual(v1, v2) except AssertionError: print(key, v1, v2) raise else: if v1 != v2: self.fail('Dictionaries differ: key=%s value1=%r value2=%r' % (key, v1, v2)) def assertEqual(self, a, b): if a == b: return # Repeat comparison with debug-level logging import logging level = logging.root.level logging.root.setLevel(logging.DEBUG) a == b logging.root.setLevel(level) self.fail('%s != %s' % (a,b)) def assertArrayAlmostEqual(self, a, b, tol=1e-7): a = np.array(a) b = np.array(b) self.assertEqual(a.shape, b.shape) if np.isnan(a).any() or np.isnan(b).any(): print('a') print(a) print('b') print(b) self.fail('Not a number (NaN) found in array') if a.dtype.kind != 'f': self.assertTrue((a == b).all()) else: absdiff = abs(a-b) if absdiff.max() > tol: loc = np.unravel_index(absdiff.argmax(), absdiff.shape) print('a') print(a) print() print('b') print(b) print() print('Absolute difference') print(absdiff) self.fail('Maximum abs difference between array elements is %e at location %r' % (absdiff.max(), loc)) def assertAtomsAlmostEqual(self, a, b, tol=1e-7): self.assertArrayAlmostEqual(a.positions, b.positions, tol) self.assertArrayAlmostEqual(a.numbers, b.numbers) self.assertArrayAlmostEqual(a._cell, b._cell) self.assertArrayAlmostEqual(a._pbc, b._pbc) def skip(f): """ Decorator which can be used to skip unit tests """ def g(self): logging.warning('skipping test %s' % f.__name__) return g
4,918
35.169118
104
py
matscipy
matscipy-master/tests/test_numpy_tricks.py
# # Copyright 2014-2015, 2017, 2021 Lars Pastewka (U. Freiburg) # 2020 Wolfram G. Nöhring (U. Freiburg) # 2015 Adrien Gola (KIT) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import numpy as np from matscipy.numpy_tricks import mabincount def test_mabincount(): w = np.array([[0.5, 1, 1], [2, 2, 2]]) x = np.array([1, 2]) r = mabincount(x, w, 4, axis=0) assert r.shape == (4, 3) np.testing.assert_allclose(r, [[0, 0, 0], [0.5, 1, 1], [2, 2, 2], [0, 0, 0]]) x = np.array([1, 2, 2]) r = mabincount(x, w.T, 4, axis=0) assert r.shape == (4, 2) np.testing.assert_allclose(r, [[0, 0], [0.5, 2], [2, 4], [0, 0]])
1,426
32.97619
81
py
matscipy
matscipy-master/tests/test_pressurecoupling.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2020, 2022 Thomas Reichenbach (Fraunhofer IWM) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import unittest import matscipytest from matscipy import pressurecoupling as pc from ase.build import fcc111 from ase.calculators.emt import EMT from ase.units import GPa, kB, fs, m, s from ase.md.langevin import Langevin from ase.md.velocitydistribution import MaxwellBoltzmannDistribution import numpy as np from io import StringIO from ase.data import atomic_masses class TestPressureCoupling(matscipytest.MatSciPyTestCase): def test_damping(self): """ Test damping classes of pressure coupling module """ atoms = fcc111('Al', size=(1, 2, 2), orthogonal=True) atoms.set_pbc(True) atoms.center(axis=2, vacuum=10.0) top_mask = np.array([False, False, True, True]) bottom_mask = np.array([True, True, False, False]) damping = pc.AutoDamping(C11=100 * GPa, p_c=0.2) slider = pc.SlideWithNormalPressureCuboidCell( top_mask, bottom_mask, 2, 0, 0, 1 * m / s, damping) M, gamma = damping.get_M_gamma(slider, atoms) A = atoms.get_cell()[0][0] * atoms.get_cell()[1][1] h = atoms[2].position[2] - atoms[0].position[2] lx = atoms.get_cell()[0][0] self.assertAlmostEqual(M, 1/(4*np.pi**2) * np.sqrt(1/0.2**2 - 1) * 100 * GPa * A / h * lx**2 / 0.01**2 * (1000 * fs)**2, places=5) self.assertAlmostEqual(gamma, 2 * np.sqrt(M * 100 * GPa * A / h), places=5) damping = pc.FixedDamping(1, 1) slider = pc.SlideWithNormalPressureCuboidCell( top_mask, bottom_mask, 2, 0, 0, 1 * m / s, damping) M, gamma = damping.get_M_gamma(slider, atoms) self.assertAlmostEqual(M, 2 * atomic_masses[13], places=5) self.assertAlmostEqual(gamma, 1, places=5) damping = pc.FixedMassCriticalDamping(C11=100 * GPa, M_factor=2) slider = pc.SlideWithNormalPressureCuboidCell( top_mask, bottom_mask, 2, 0, 0, 1 * m / s, damping) M, gamma = damping.get_M_gamma(slider, atoms) self.assertAlmostEqual(M, 2 * 2 * atomic_masses[13], places=5) self.assertAlmostEqual(gamma, 2 * np.sqrt(M * 100 * GPa * A / h), places=5) def test_slider(self): """ Test SlideWithNormalPressureCuboidCell class """ atoms = fcc111('Al', size=(1, 2, 2), orthogonal=True) atoms.set_pbc(True) atoms.center(axis=2, vacuum=10.0) top_mask = np.array([False, False, True, True]) bottom_mask = np.array([True, True, False, False]) calc = EMT() atoms.calc = calc damping = pc.AutoDamping(C11=100 * GPa, p_c=0.2) slider = pc.SlideWithNormalPressureCuboidCell( top_mask, bottom_mask, 2, 1 * GPa, 0, 1 * m / s, damping) self.assertEqual(slider.Tdir, 1) self.assertEqual(np.sum(slider.middle_mask), 0) self.assertAlmostEqual(slider.get_A(atoms), atoms.get_cell()[0][0] * atoms.get_cell()[1][1], places=5) forces = atoms.get_forces() Fz = forces[top_mask, 2].sum() atoms.set_velocities([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) vz = atoms.get_velocities()[top_mask, 2].sum() / np.sum(top_mask) M, gamma = damping.get_M_gamma(slider, atoms) scale = atoms.get_masses()[top_mask].sum() / M slider.adjust_forces(atoms, forces) self.assertEqual(np.sum(np.abs(forces[0])), 0) self.assertEqual(np.sum(np.abs(forces[1])), 0) self.assertEqual(np.sum(np.abs(forces[2][:2])), 0) self.assertEqual(np.sum(np.abs(forces[3][:2])), 0) self.assertEqual(forces[2][2], forces[3][2]) self.assertAlmostEqual(forces[2][2], (Fz - GPa * slider.get_A(atoms) - gamma * vz) * scale / np.sum(top_mask), places=5) momenta = atoms.get_momenta() mom_z = momenta[top_mask, 2].sum() / np.sum(top_mask) slider.adjust_momenta(atoms, momenta) self.assertEqual(np.sum(np.abs(momenta[0])), 0) self.assertEqual(np.sum(np.abs(momenta[1])), 0) self.assertEqual(momenta[2][1], 0) self.assertEqual(momenta[3][1], 0) self.assertAlmostEqual(momenta[2][0], m/s * atomic_masses[13], places=7) self.assertAlmostEqual(momenta[3][0], m/s * atomic_masses[13], places=7) self.assertAlmostEqual(momenta[2][2], mom_z, places=5) self.assertAlmostEqual(momenta[3][2], mom_z, places=5) def test_logger(self): """ Test SlideLogger and SlideLog classes """ atoms = fcc111('Al', size=(4, 4, 9), orthogonal=True) atoms.set_pbc(True) atoms.center(axis=2, vacuum=10.0) calc = EMT() atoms.calc = calc damping = pc.AutoDamping(C11=1 * GPa, p_c=0.2) z = atoms.positions[:, 2] top_mask = z > z[115] - 0.1 bottom_mask = z < z[19] + 0.1 Pdir = 2 vdir = 0 P = 1 * GPa v = 1.0 * m / s dt = 0.5 * fs T = 300.0 t_langevin = 75 * fs gamma_langevin = 1. / t_langevin slider = pc.SlideWithNormalPressureCuboidCell( top_mask, bottom_mask, Pdir, P, vdir, v, damping) atoms.set_constraint(slider) temps = np.zeros((len(atoms), 3)) temps[slider.middle_mask, slider.Tdir] = T gammas = np.zeros((len(atoms), 3)) gammas[slider.middle_mask, slider.Tdir] = gamma_langevin integrator = Langevin(atoms, dt, temperature_K=temps, friction=gammas, fixcm=False) forces_ini = atoms.get_forces(apply_constraint=False) forces_ini_const = atoms.get_forces(apply_constraint=True) h_ini = atoms[115].position[2] - atoms[19].position[2] A = atoms.get_cell()[0][0] * atoms.get_cell()[1][1] handle = StringIO() beginning = handle.tell() logger = pc.SlideLogger(handle, atoms, slider, integrator) logger.write_header() integrator.attach(logger) integrator.run(1) integrator.logfile.close() handle.seek(beginning) log = pc.SlideLog(handle) self.assertArrayAlmostEqual(log.step, np.array([0, 1])) self.assertArrayAlmostEqual(log.time, np.array([0, 0.5])) self.assertEqual(log.T_thermostat[0], 0) Tref = (atomic_masses[13] * (atoms.get_velocities()[slider.middle_mask, 1]**2).sum() / (np.sum(slider.middle_mask) * kB)) self.assertAlmostEqual(log.T_thermostat[1], Tref, places=5) self.assertAlmostEqual(log.P_top[0], forces_ini[slider.top_mask, 2].sum() / A / GPa, places=5) self.assertAlmostEqual(log.P_top[1], atoms.get_forces( apply_constraint=False)[slider.top_mask, 2].sum() / A / GPa, places=5) self.assertAlmostEqual(log.P_bottom[0], forces_ini[slider.bottom_mask, 2].sum() / A / GPa, places=5) self.assertAlmostEqual(log.P_bottom[1], atoms.get_forces( apply_constraint=False)[slider.bottom_mask, 2].sum() / A / GPa, places=5) self.assertArrayAlmostEqual(log.h, [h_ini, atoms[115].position[2] - atoms[19].position[2]]) self.assertArrayAlmostEqual(log.v, [0, atoms.get_velocities()[115][2] * fs]) self.assertArrayAlmostEqual(log.a, [forces_ini_const[115][2] / atomic_masses[13] * fs**2, atoms.get_forces( apply_constraint=True)[115][2] / atomic_masses[13] * fs**2]) self.assertAlmostEqual(log.tau_top[0], forces_ini[top_mask, 0].sum() / A / GPa, places=13) self.assertAlmostEqual(log.tau_top[1], atoms.get_forces( apply_constraint=False)[top_mask, 0].sum() / A / GPa, places=13) self.assertAlmostEqual(log.tau_bottom[0], forces_ini[bottom_mask, 0].sum() / A / GPa, places=13) self.assertAlmostEqual(log.tau_bottom[1], atoms.get_forces(apply_constraint=False) [bottom_mask, 0].sum() / A / GPa, places=13) handle.close() def test_usage(self): """ Test if sliding simulation with pressure coupling module runs without errors """ atoms = fcc111('Al', size=(4, 4, 9), orthogonal=True) atoms.set_pbc(True) atoms.center(axis=2, vacuum=10.0) z = atoms.positions[:, 2] top_mask = z > z[115] - 0.1 bottom_mask = z < z[19] + 0.1 calc = EMT() atoms.calc = calc damping = pc.AutoDamping(C11=500 * GPa, p_c=0.2) Pdir = 2 vdir = 0 P = 5 * GPa v = 100.0 * m / s dt = 1.0 * fs T = 400.0 t_langevin = 75 * fs gamma_langevin = 1. / t_langevin slider = pc.SlideWithNormalPressureCuboidCell( top_mask, bottom_mask, Pdir, P, vdir, v, damping ) atoms.set_constraint(slider) MaxwellBoltzmannDistribution(atoms, temperature_K=2 * T) atoms.arrays['momenta'][top_mask, :] = 0 atoms.arrays['momenta'][bottom_mask, :] = 0 handle = StringIO() beginning = handle.tell() temps = np.zeros((len(atoms), 3)) temps[slider.middle_mask, slider.Tdir] = T gammas = np.zeros((len(atoms), 3)) gammas[slider.middle_mask, slider.Tdir] = gamma_langevin integrator = Langevin(atoms, dt, temperature_K=temps, friction=gammas, fixcm=False) logger = pc.SlideLogger(handle, atoms, slider, integrator) logger.write_header() integrator.attach(logger) integrator.run(10) integrator.logfile.close() handle.seek(beginning) pc.SlideLog(handle) handle.close() if __name__ == '__main__': unittest.main()
12,069
40.477663
79
py
matscipy
matscipy-master/tests/test_poisson_nernst_planck_solver.py
# # Copyright 2019-2020 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import matscipytest import numpy as np import os.path import unittest from matscipy.electrochemistry import PoissonNernstPlanckSystem class PoissonNernstPlanckSolverTest(matscipytest.MatSciPyTestCase): def setUp(self): """Provides 0.1 mM NaCl solution at 0.05 V across 100 nm open half space reference data from binary npz file""" self.test_path = os.path.dirname(os.path.abspath(__file__)) self.ref_data = np.load( os.path.join(self.test_path, 'electrochemistry_data', 'NaCl_c_0.1_mM_0.1_mM_z_+1_-1_L_1e-7_u_0.05_V_seg_200_interface.npz') ) def test_poisson_nernst_planck_solver_std_interface_bc(self): """Tests PNP solver against simple interfacial BC""" pnp = PoissonNernstPlanckSystem( c=[0.1,0.1], z=[1,-1], L=1e-7, delta_u=0.05, N=200, e=1e-12, maxit=20) pnp.useStandardInterfaceBC() pnp.solve() self.assertArrayAlmostEqual(pnp.grid, self.ref_data ['x']) self.assertArrayAlmostEqual(pnp.potential, self.ref_data ['u']) self.assertArrayAlmostEqual(pnp.concentration, self.ref_data ['c'], 1e-6) if __name__ == '__main__': unittest.main()
1,986
38.74
119
py
matscipy
matscipy-master/tests/test_atomic_strain.py
# # Copyright 2014, 2020-2021 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import ase.io as io from ase.lattice.cubic import Diamond import matscipytest from matscipy.neighbours import mic, neighbour_list from matscipy.atomic_strain import (get_delta_plus_epsilon_dgesv, get_delta_plus_epsilon, get_D_square_min) ### class TestAtomicStrain(matscipytest.MatSciPyTestCase): def test_dsygv_dgelsd(self): a = Diamond('C', size=[4,4,4]) b = a.copy() b.positions += (np.random.random(b.positions.shape)-0.5)*0.1 i, j = neighbour_list("ij", b, 1.85) dr_now = mic(b.positions[i] - b.positions[j], b.cell) dr_old = mic(a.positions[i] - a.positions[j], a.cell) dgrad1 = get_delta_plus_epsilon_dgesv(len(b), i, dr_now, dr_old) dgrad2 = get_delta_plus_epsilon(len(b), i, dr_now, dr_old) self.assertArrayAlmostEqual(dgrad1, dgrad2) ### if __name__ == '__main__': unittest.main()
2,827
34.797468
72
py
matscipy
matscipy-master/tests/test_eam_calculator.py
#! /usr/bin/env python # # Copyright 2014-2015, 2017, 2019-2021 Lars Pastewka (U. Freiburg) # 2019-2020 Wolfram G. Nöhring (U. Freiburg) # 2020 Johannes Hoermann (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import gzip import random import unittest import numpy as np from numpy.linalg import norm import ase.io as io from ase.calculators.test import numeric_force from ase.constraints import StrainFilter, UnitCellFilter from ase.lattice.compounds import B1, B2, L1_0, L1_2 from ase.lattice.cubic import FaceCenteredCubic from ase.lattice.hexagonal import HexagonalClosedPacked from ase.optimize import FIRE from ase.units import GPa import matscipytest from matscipy.elasticity import fit_elastic_constants, Voigt_6x6_to_cubic from matscipy.neighbours import neighbour_list from matscipy.numerical import numerical_stress from matscipy.calculators.eam import EAM ### class TestEAMCalculator(matscipytest.MatSciPyTestCase): disp = 1e-6 tol = 2e-6 def test_forces(self): for calc in [EAM('Au-Grochola-JCP05.eam.alloy')]: a = io.read('Au_923.xyz') a.center(vacuum=10.0) a.calc = calc f = a.get_forces() for i in range(9): atindex = i*100 fn = [numeric_force(a, atindex, 0, self.disp), numeric_force(a, atindex, 1, self.disp), numeric_force(a, atindex, 2, self.disp)] self.assertArrayAlmostEqual(f[atindex], fn, tol=self.tol) def test_stress(self): a = FaceCenteredCubic('Au', size=[2,2,2]) calc = EAM('Au-Grochola-JCP05.eam.alloy') a.calc = calc self.assertArrayAlmostEqual(a.get_stress(), numerical_stress(a), tol=self.tol) sx, sy, sz = a.cell.diagonal() a.set_cell([sx, 0.9*sy, 1.2*sz], scale_atoms=True) self.assertArrayAlmostEqual(a.get_stress(), numerical_stress(a), tol=self.tol) a.set_cell([[sx, 0.1*sx, 0], [0, 0.9*sy, 0], [0, -0.1*sy, 1.2*sz]], scale_atoms=True) self.assertArrayAlmostEqual(a.get_stress(), numerical_stress(a), tol=self.tol) def test_Grochola(self): a = FaceCenteredCubic('Au', size=[2,2,2]) calc = EAM('Au-Grochola-JCP05.eam.alloy') a.calc = calc FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) a0 = a.cell.diagonal().mean()/2 self.assertTrue(abs(a0-4.0701)<2e-5) self.assertTrue(abs(a.get_potential_energy()/len(a)+3.924)<0.0003) C, C_err = fit_elastic_constants(a, symmetry='cubic', verbose=False) C11, C12, C44 = Voigt_6x6_to_cubic(C) self.assertTrue(abs((C11-C12)/GPa-32.07)<0.7) self.assertTrue(abs(C44/GPa-45.94)<0.5) def test_direct_evaluation(self): a = FaceCenteredCubic('Au', size=[2,2,2]) a.rattle(0.1) calc = EAM('Au-Grochola-JCP05.eam.alloy') a.calc = calc f = a.get_forces() calc2 = EAM('Au-Grochola-JCP05.eam.alloy') i_n, j_n, dr_nc, abs_dr_n = neighbour_list('ijDd', a, cutoff=calc2.cutoff) epot, virial, f2 = calc2.energy_virial_and_forces(a.numbers, i_n, j_n, dr_nc, abs_dr_n) self.assertArrayAlmostEqual(f, f2) a = FaceCenteredCubic('Cu', size=[2,2,2]) calc = EAM('CuAg.eam.alloy') a.calc = calc FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e_Cu = a.get_potential_energy()/len(a) a = FaceCenteredCubic('Ag', size=[2,2,2]) a.calc = calc FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e_Ag = a.get_potential_energy()/len(a) self.assertTrue(abs(e_Ag+2.85)<1e-6) a = L1_2(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.calc = calc FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.096)<0.0005) a = B1(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.calc = calc FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.516)<0.0005) a = B2(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.calc = calc FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.177)<0.0003) a = L1_2(['Cu', 'Ag'], size=[2,2,2], latticeconstant=4.0) a.calc = calc FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.083)<0.0005) def test_CuZr(self): # This is a test for the potential published in: # Mendelev, Sordelet, Kramer, J. Appl. Phys. 102, 043501 (2007) a = FaceCenteredCubic('Cu', size=[2,2,2]) calc = EAM('CuZr_mm.eam.fs', kind='eam/fs') a.calc = calc FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) a_Cu = a.cell.diagonal().mean()/2 #print('a_Cu (3.639) = ', a_Cu) self.assertAlmostEqual(a_Cu, 3.639, 3) a = HexagonalClosedPacked('Zr', size=[2,2,2]) a.calc = calc FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=1e-3) a, b, c = a.cell/2 print('a_Zr (3.220) = ', norm(a), norm(b)) print('c_Zr (5.215) = ', norm(c)) self.assertAlmostEqual(norm(a), 3.220, 3) self.assertAlmostEqual(norm(b), 3.220, 3) self.assertAlmostEqual(norm(c), 5.215, 3) # CuZr3 a = L1_2(['Cu', 'Zr'], size=[2,2,2], latticeconstant=4.0) a.calc = calc FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) self.assertAlmostEqual(a.cell.diagonal().mean()/2, 4.324, 3) # Cu3Zr a = L1_2(['Zr', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.calc = calc FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) self.assertAlmostEqual(a.cell.diagonal().mean()/2, 3.936, 3) # CuZr a = B2(['Zr', 'Cu'], size=[2,2,2], latticeconstant=3.3) a.calc = calc FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) self.assertAlmostEqual(a.cell.diagonal().mean()/2, 3.237, 3) def test_forces_CuZr_glass(self): """Calculate interatomic forces in CuZr glass Reference: tabulated forces from a calculation with Lammmps (git version patch_29Mar2019-2-g585403d65) The forces can be re-calculated using the following Lammps commands: units metal atom_style atomic boundary p p p read_data CuZr_glass_460_atoms.lammps.data.gz pair_style eam/alloy pair_coeff * * ZrCu.onecolumn.eam.alloy Zr Cu # The initial configuration is in equilibrium # and the remaining forces are small # Swap atom types to bring system out of # equilibrium and create nonzero forces group originally_Zr type 1 group originally_Cu type 2 set group originally_Zr type 2 set group originally_Cu type 1 run 0 write_dump all custom & CuZr_glass_460_atoms_forces.lammps.dump.gz & id type x y z fx fy fz & modify sort id format float "%.14g" """ format = "lammps-dump" if "lammps-dump" in io.formats.all_formats.keys() else "lammps-dump-text" atoms = io.read("CuZr_glass_460_atoms_forces.lammps.dump.gz", format=format) old_atomic_numbers = atoms.get_atomic_numbers() sel, = np.where(old_atomic_numbers == 1) new_atomic_numbers = np.zeros_like(old_atomic_numbers) new_atomic_numbers[sel] = 40 # Zr sel, = np.where(old_atomic_numbers == 2) new_atomic_numbers[sel] = 29 # Cu atoms.set_atomic_numbers(new_atomic_numbers) calculator = EAM('ZrCu.onecolumn.eam.alloy') atoms.calc = calculator atoms.pbc = [True, True, True] forces = atoms.get_forces() # Read tabulated forces and compare with gzip.open("CuZr_glass_460_atoms_forces.lammps.dump.gz") as file: for line in file: if line.startswith(b"ITEM: ATOMS "): # ignore header break dump = np.loadtxt(file) forces_dump = dump[:, 5:8] self.assertArrayAlmostEqual(forces, forces_dump, tol=1e-3) def test_funcfl(self): """Test eam kind 'eam' (DYNAMO funcfl format) variable da equal 0.02775 variable amin equal 2.29888527117067752084 variable amax equal 5.55*sqrt(2.0) variable i loop 201 label loop_head clear variable lattice_parameter equal ${amin}+${da}*${i} units metal atom_style atomic boundary p p p lattice fcc ${lattice_parameter} region box block 0 5 0 5 0 5 create_box 1 box pair_style eam pair_coeff * * Au_u3.eam create_atoms 1 box thermo 1 run 0 variable x equal pe variable potential_energy_fmt format x "%.14f" print "#a,E: ${lattice_parameter} ${potential_energy_fmt}" next i jump SELF loop_head # use # grep '^#a,E' log.lammps | awk '{print $2,$3}' > aE.txt # to extract info from log file The reference data was calculated using Lammps (git commit a73f1d4f037f670cd4295ecc1a576399a31680d2). """ da = 0.02775 amin = 2.29888527117067752084 amax = 5.55 * np.sqrt(2.0) for i in range(1, 202): latticeconstant = amin + i * da atoms = FaceCenteredCubic(symbol='Au', size=[5,5,5], pbc=(1,1,1), latticeconstant=latticeconstant) calc = EAM('Au-Grochola-JCP05.eam.alloy') atoms.calc = calc energy = atoms.get_potential_energy() print(energy) ### if __name__ == '__main__': unittest.main()
11,672
39.53125
110
py
matscipy
matscipy-master/tests/test_opls.py
# # Copyright 2023 Andreas Klemenz (Fraunhofer IWM) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import sys import io import unittest import numpy as np import ase import matscipy.opls class TestOPLS(unittest.TestCase): def test_bond_data(self): """Test the matscipy.opls.BondData class.""" bond_data = matscipy.opls.BondData({'AB-CD': [1, 2], 'EF-GH': [3, 4]}) self.assertDictEqual(bond_data.nvh, {'AB-CD': [1, 2], 'EF-GH': [3, 4]}) # check correct handling of permutations and missing values bond_data.set_names(['A1-A2', 'A2-A1']) self.assertSetEqual(bond_data.names, {'AB-CD', 'EF-GH', 'A1-A2'}) self.assertIsNone(bond_data.get_name('A0', 'A0')) self.assertMultiLineEqual(bond_data.get_name('A1', 'A2'), 'A1-A2') self.assertMultiLineEqual(bond_data.get_name('A2', 'A1'), 'A1-A2') # check return values self.assertTupleEqual(bond_data.name_value('A0', 'A0'), (None, None)) self.assertTupleEqual(bond_data.name_value('AB', 'CD'), ('AB-CD', [1, 2])) self.assertTupleEqual(bond_data.name_value('CD', 'AB'), ('AB-CD', [1, 2])) self.assertListEqual(bond_data.get_value('AB', 'CD'), [1, 2]) def test_cutoff_data(self): """Test the matscipy.opls.CutoffList class.""" cutoff_data = matscipy.opls.CutoffList({'AB-CD': 1.0, 'EF-GH': 2.0}) self.assertAlmostEqual(cutoff_data.max(), 2.0, places=5) def test_angles_data(self): """Test the matscipy.opls.AnglesData class.""" angles_data = matscipy.opls.AnglesData({'A1-A2-A3': [1, 2], 'A4-A5-A6': [3, 4]}) self.assertDictEqual(angles_data.nvh, {'A1-A2-A3': [1, 2], 'A4-A5-A6': [3, 4]}) # check correct handling of permutations and missing values angles_data.set_names(['A7-A8-A9', 'A9-A8-A7']) self.assertSetEqual(angles_data.names, {'A1-A2-A3', 'A4-A5-A6', 'A7-A8-A9'}) angles_data.add_name('B1', 'B2', 'B3') angles_data.add_name('B3', 'B2', 'B1') self.assertSetEqual(angles_data.names, {'A1-A2-A3', 'A4-A5-A6', 'A7-A8-A9', 'B1-B2-B3'}) self.assertIsNone(angles_data.get_name('A0', 'A0', 'A0')) self.assertMultiLineEqual(angles_data.get_name('A1', 'A2', 'A3'), 'A1-A2-A3') self.assertMultiLineEqual(angles_data.get_name('A3', 'A2', 'A1'), 'A1-A2-A3') # check return values self.assertTupleEqual(angles_data.name_value('A0', 'A0', 'A0'), (None, None)) self.assertTupleEqual( angles_data.name_value('A1', 'A2', 'A3'), ('A1-A2-A3', [1, 2]) ) self.assertTupleEqual( angles_data.name_value('A3', 'A2', 'A1'), ('A1-A2-A3', [1, 2]) ) def test_dihedrals_data(self): """Test the matscipy.opls.DihedralsData class.""" dih_data = matscipy.opls.DihedralsData({'A1-A2-A3-A4': [1, 2, 3, 4], 'B1-B2-B3-B4': [5, 6, 7, 8]}) self.assertDictEqual(dih_data.nvh, {'A1-A2-A3-A4': [1, 2, 3, 4], 'B1-B2-B3-B4': [5, 6, 7, 8]}) # check correct handling of permutations and missing values dih_data.set_names(['C1-C2-C3-C4', 'C4-C3-C2-C1']) self.assertSetEqual( dih_data.names, {'A1-A2-A3-A4', 'B1-B2-B3-B4', 'C1-C2-C3-C4'} ) dih_data.add_name('D1', 'D2', 'D3', 'D4') dih_data.add_name('D4', 'D3', 'D2', 'D1') self.assertSetEqual(dih_data.names, {'A1-A2-A3-A4', 'B1-B2-B3-B4', 'C1-C2-C3-C4', 'D1-D2-D3-D4'}) self.assertIsNone(dih_data.get_name('A0', 'A0', 'A0', 'A0')) self.assertMultiLineEqual( dih_data.get_name('A1', 'A2', 'A3', 'A4'), 'A1-A2-A3-A4' ) self.assertMultiLineEqual( dih_data.get_name('A4', 'A3', 'A2', 'A1'), 'A1-A2-A3-A4' ) # check return values self.assertTupleEqual( dih_data.name_value('A0', 'A0', 'A0', 'A0'), (None, None) ) self.assertTupleEqual( dih_data.name_value('A1', 'A2', 'A3', 'A4'), ('A1-A2-A3-A4', [1, 2, 3, 4]) ) self.assertTupleEqual( dih_data.name_value('A4', 'A3', 'A2', 'A1'), ('A1-A2-A3-A4', [1, 2, 3, 4]) ) def test_opls_structure(self): """Test the matscipy.opls.OPLSStructure class.""" # check initialization c2h6 = ase.Atoms('C2H6', cell=[10., 10., 10.]) opls_c2h6 = matscipy.opls.OPLSStructure(c2h6) self.assertListEqual(opls_c2h6.get_types().tolist(), ['C', 'H']) # check correct initial assignment of tags self.assertListEqual(opls_c2h6.types[opls_c2h6.get_tags()].tolist(), opls_c2h6.get_chemical_symbols()) # check correct initial assignment of # tags after definition of atom types types = ['C1', 'C1', 'H1', 'H1', 'H1', 'H2', 'H2', 'H2'] opls_c2h6.set_types(types) self.assertListEqual( opls_c2h6.get_types()[opls_c2h6.get_tags()].tolist(), types ) opls_c2h6.set_positions([ [1., 0., 0.], [2., 0., 0.], [0., 0., 0.], [1., 1., 0.], [1., -1., 0.], [2., 0., 1.], [2., 0., -1.], [3., 0., 0.] ]) opls_c2h6.center() # check that a runtime error is raised # in case some cutoffs are not defined cutoffs = matscipy.opls.CutoffList( {'C1-H1': 1.1, 'C1-H2': 1.1, 'H1-H2': 0.1, 'H1-H1': 0.1, 'H2-H2': 0.1} ) opls_c2h6.set_cutoffs(cutoffs) with self.assertRaises(RuntimeError): opls_c2h6.get_neighbors() # check for correct neighborlist when all cutoffs are defined cutoffs = matscipy.opls.CutoffList( {'C1-C1': 1.1, 'C1-H1': 1.1, 'C1-H2': 1.1, 'H1-H2': 0.1, 'H1-H1': 0.1, 'H2-H2': 0.1} ) opls_c2h6.set_cutoffs(cutoffs) opls_c2h6.get_neighbors() pairs = [(0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 5), (1, 6), (1, 7), (2, 0), (3, 0), (4, 0), (5, 1), (6, 1), (7, 1) ] for i, j in zip(opls_c2h6.ibond, opls_c2h6.jbond): self.assertTrue((i, j) in pairs) # check atomic charges opls_c2h6.set_atom_data({'C1': [1, 2, 3], 'H1': [4, 5, 6], 'H2': [7, 8, 9]}) for charge, charge_target in zip(opls_c2h6.get_charges(), [3., 3., 6., 6., 6., 9., 9., 9.]): self.assertAlmostEqual(charge, charge_target, places=5) # Check correct construction of bond type list and bond list # Case 1: Some cutoffs are not defined - check for runtime error cutoffs = matscipy.opls.CutoffList( {'C1-H1': 1.1, 'C1-H2': 1.1, 'H1-H2': 0.1, 'H1-H1': 0.1, 'H2-H2': 0.1} ) opls_c2h6.set_cutoffs(cutoffs) with self.assertRaises(RuntimeError): opls_c2h6.get_bonds() # Case 2: All cutoffs are defined cutoffs = matscipy.opls.CutoffList( {'C1-C1': 1.1, 'C1-H1': 1.1, 'C1-H2': 1.1, 'H1-H2': 0.1, 'H1-H1': 0.1, 'H2-H2': 0.1} ) opls_c2h6.set_cutoffs(cutoffs) # Case 2.1: no bond data provided # Case 2.2: bond data is provided and complete # Valid lists should be created in both cases bond_data = matscipy.opls.BondData({'C1-C1': [1, 2], 'C1-H1': [3, 4], 'C1-H2': [5, 6]}) for bond_types, bond_list in [opls_c2h6.get_bonds(), opls_c2h6.get_bonds(bond_data)]: # Check for correct list of bond types self.assertEqual(bond_types.shape[0], 3) self.assertTrue('C1-C1' in bond_types) self.assertTrue('H1-C1' in bond_types or 'C1-H1' in bond_types) self.assertTrue('H2-C1' in bond_types or 'C1-H2' in bond_types) # Check for correct list of bonds type_index_c1c1 = np.where(bond_types == 'C1-C1')[0][0] if 'H1-C1' in bond_types: type_index_c1h1 = np.where(bond_types == 'H1-C1')[0][0] else: type_index_c1h1 = np.where(bond_types == 'C1-H1')[0][0] if 'H2-C1' in bond_types: type_index_c1h2 = np.where(bond_types == 'H2-C1')[0][0] else: type_index_c1h2 = np.where(bond_types == 'C1-H2')[0][0] self.assertEqual(bond_list.shape[0], 7) bond_list = bond_list.tolist() self.assertTrue([type_index_c1c1, 0, 1] in bond_list or [type_index_c1c1, 1, 0] in bond_list) self.assertTrue([type_index_c1h1, 0, 2] in bond_list or [type_index_c1h1, 2, 0] in bond_list) self.assertTrue([type_index_c1h1, 0, 3] in bond_list or [type_index_c1h1, 3, 0] in bond_list) self.assertTrue([type_index_c1h1, 0, 4] in bond_list or [type_index_c1h1, 4, 0] in bond_list) self.assertTrue([type_index_c1h2, 1, 5] in bond_list or [type_index_c1h2, 5, 1] in bond_list) self.assertTrue([type_index_c1h2, 1, 6] in bond_list or [type_index_c1h2, 6, 1] in bond_list) self.assertTrue([type_index_c1h2, 1, 7] in bond_list or [type_index_c1h2, 7, 1] in bond_list) # check that a runtime error is raised in # case bond data is provided but incomplete buf = io.StringIO() sys.stdout = buf # suppress STDOUT while running test with self.assertRaises(RuntimeError): opls_c2h6.get_bonds(matscipy.opls.BondData({'C1-C1': [1, 2], 'C1-H1': [3, 4]})) sys.stdout = sys.__stdout__ # Check correct construction of angle type list and angle list # Case 1: no angular potentials provided # Case 2: angular potentials are provided and complete # Valid lists should be created in both cases angles_data = matscipy.opls.AnglesData( {'H1-C1-H1': [1, 2], 'H2-C1-H2': [3, 4], 'C1-C1-H1': [5, 6], 'C1-C1-H2': [7, 8]} ) for angle_types, angle_list in [opls_c2h6.get_angles(), opls_c2h6.get_angles(angles_data)]: # Check for correct list of angle types self.assertEqual(len(angle_types), 4) self.assertTrue('H1-C1-H1' in angle_types) self.assertTrue('H2-C1-H2' in angle_types) self.assertTrue('C1-C1-H1' in angle_types or 'H1-C1-C1' in angle_types) self.assertTrue('C1-C1-H2' in angle_types or 'H2-C1-C1' in angle_types) # Check for correct list of angles type_index_h1c1h1 = angle_types.index('H1-C1-H1') type_index_h2c1h2 = angle_types.index('H2-C1-H2') if 'C1-C1-H1' in angle_types: type_index_c1c1h1 = angle_types.index('C1-C1-H1') else: type_index_c1c1h1 = angle_types.index('H1-C1-C1') if 'C1-C1-H2' in angle_types: type_index_c1c1h2 = angle_types.index('C1-C1-H2') else: type_index_c1c1h2 = angle_types.index('H2-C1-C1') self.assertEqual(len(angle_list), 12) self.assertTrue([type_index_c1c1h1, 2, 0, 1] in angle_list or [type_index_c1c1h1, 1, 0, 2] in angle_list) self.assertTrue([type_index_c1c1h1, 3, 0, 1] in angle_list or [type_index_c1c1h1, 1, 0, 3] in angle_list) self.assertTrue([type_index_c1c1h1, 4, 0, 1] in angle_list or [type_index_c1c1h1, 1, 0, 4] in angle_list) self.assertTrue([type_index_c1c1h2, 5, 1, 0] in angle_list or [type_index_c1c1h2, 0, 1, 5] in angle_list) self.assertTrue([type_index_c1c1h2, 6, 1, 0] in angle_list or [type_index_c1c1h2, 0, 1, 6] in angle_list) self.assertTrue([type_index_c1c1h2, 7, 1, 0] in angle_list or [type_index_c1c1h2, 0, 1, 7] in angle_list) self.assertTrue([type_index_h1c1h1, 2, 0, 3] in angle_list or [type_index_h1c1h1, 3, 0, 2] in angle_list) self.assertTrue([type_index_h1c1h1, 2, 0, 4] in angle_list or [type_index_h1c1h1, 4, 0, 2] in angle_list) self.assertTrue([type_index_h1c1h1, 3, 0, 4] in angle_list or [type_index_h1c1h1, 4, 0, 3] in angle_list) self.assertTrue([type_index_h2c1h2, 6, 1, 5] in angle_list or [type_index_h2c1h2, 5, 1, 6] in angle_list) self.assertTrue([type_index_h2c1h2, 7, 1, 5] in angle_list or [type_index_h2c1h2, 5, 1, 7] in angle_list) self.assertTrue([type_index_h2c1h2, 7, 1, 6] in angle_list or [type_index_h2c1h2, 6, 1, 7] in angle_list) # check that a runtime error is raised in case # angular potentials are provided but incomplete buf = io.StringIO() sys.stdout = buf # suppress STDOUT while running test angles_data = matscipy.opls.AnglesData( {'H1-C1-H1': [1, 2], 'H2-C1-H2': [3, 4], 'C1-C1-H1': [5, 6]} ) with self.assertRaises(RuntimeError): angle_types, angle_list = opls_c2h6.get_angles(angles_data) sys.stdout = sys.__stdout__ # Check correct construction of dihedral type list and dihedral list # Case 1: no dihedral potentials provided # Case 2: dihedral potentials are provided and complete # Valid lists should be created in both cases dih_data = matscipy.opls.DihedralsData({'H1-C1-C1-H2': [1, 2, 3, 4]}) for dih_types, dih_list in [opls_c2h6.get_dihedrals(), opls_c2h6.get_dihedrals(dih_data)]: # Check for correct list of dihedral types self.assertEqual(len(dih_types), 1) self.assertTrue('H1-C1-C1-H2' in dih_types or 'H2-C1-C1-H1' in dih_types) # Check for correct list of dihedrals self.assertEqual(len(dih_list), 9) self.assertTrue([0, 2, 0, 1, 5] in dih_list or [0, 5, 1, 0, 2] in dih_list) self.assertTrue([0, 3, 0, 1, 5] in dih_list or [0, 5, 1, 0, 3] in dih_list) self.assertTrue([0, 4, 0, 1, 5] in dih_list or [0, 5, 1, 0, 4] in dih_list) self.assertTrue([0, 2, 0, 1, 6] in dih_list or [0, 6, 1, 0, 2] in dih_list) self.assertTrue([0, 3, 0, 1, 6] in dih_list or [0, 6, 1, 0, 3] in dih_list) self.assertTrue([0, 4, 0, 1, 6] in dih_list or [0, 6, 1, 0, 4] in dih_list) self.assertTrue([0, 2, 0, 1, 7] in dih_list or [0, 7, 1, 0, 2] in dih_list) self.assertTrue([0, 3, 0, 1, 7] in dih_list or [0, 7, 1, 0, 3] in dih_list) self.assertTrue([0, 4, 0, 1, 7] in dih_list or [0, 7, 1, 0, 4] in dih_list) if __name__ == '__main__': unittest.main()
17,202
42.441919
77
py
matscipy
matscipy-master/tests/test_eam_io.py
# # Copyright 2015, 2020-2021 Lars Pastewka (U. Freiburg) # 2020 Wolfram G. Nöhring (U. Freiburg) # 2015 Adrien Gola (KIT) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # Adrien Gola, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import os from matscipy.calculators.eam.io import (read_eam, write_eam, mix_eam) try: from scipy import interpolate from matscipy.calculators.eam import EAM except: print('Warning: No scipy') interpolate = False import ase.io as io from ase.calculators.test import numeric_force from ase.constraints import StrainFilter, UnitCellFilter from ase.lattice.compounds import B1, B2, L1_0, L1_2 from ase.lattice.cubic import FaceCenteredCubic from ase.optimize import FIRE import matscipytest ### class TestEAMIO(matscipytest.MatSciPyTestCase): tol = 1e-6 def test_eam_read_write(self): source,parameters,F,f,rep = read_eam("Au_u3.eam",kind="eam") write_eam(source,parameters,F,f,rep,"Au_u3_copy.eam",kind="eam") source1,parameters1,F1,f1,rep1 = read_eam("Au_u3_copy.eam",kind="eam") os.remove("Au_u3_copy.eam") for i,p in enumerate(parameters): try: diff = p - parameters1[i] except: diff = None if diff is None: self.assertTrue(p == parameters1[i]) else: print(i, p, parameters1[i], diff, self.tol, diff < self.tol) self.assertTrue(diff < self.tol) self.assertTrue((F == F1).all()) self.assertTrue((f == f1).all()) self.assertArrayAlmostEqual(rep, rep1) def test_eam_alloy_read_write(self): source,parameters,F,f,rep = read_eam("CuAgNi_Zhou.eam.alloy",kind="eam/alloy") write_eam(source,parameters,F,f,rep,"CuAgNi_Zhou.eam.alloy_copy",kind="eam/alloy") source1,parameters1,F1,f1,rep1 = read_eam("CuAgNi_Zhou.eam.alloy_copy",kind="eam/alloy") os.remove("CuAgNi_Zhou.eam.alloy_copy") fail = 0 for i,p in enumerate(parameters): try: for j,d in enumerate(p): if d != parameters[i][j]: fail+=1 except: if p != parameters[i]: fail +=1 self.assertTrue(fail == 0) self.assertTrue((F == F1).all()) self.assertTrue((f == f1).all()) for i in range(len(rep)): for j in range(len(rep)): if j < i : self.assertTrue((rep[i,j,:] == rep1[i,j,:]).all()) def test_eam_fs_read_write(self): source,parameters,F,f,rep = read_eam("CuZr_mm.eam.fs",kind="eam/fs") write_eam(source,parameters,F,f,rep,"CuZr_mm.eam.fs_copy",kind="eam/fs") source1,parameters1,F1,f1,rep1 = read_eam("CuZr_mm.eam.fs_copy",kind="eam/fs") os.remove("CuZr_mm.eam.fs_copy") fail = 0 for i,p in enumerate(parameters): try: for j,d in enumerate(p): if d != parameters[i][j]: fail+=1 except: if p != parameters[i]: fail +=1 self.assertTrue(fail == 0) self.assertTrue((F == F1).all()) for i in range(f.shape[0]): for j in range(f.shape[0]): self.assertTrue((f[i,j,:] == f1[i,j,:]).all()) for i in range(len(rep)): for j in range(len(rep)): if j < i : self.assertTrue((rep[i,j,:] == rep1[i,j,:]).all()) def test_mix_eam_alloy(self): if False: source,parameters,F,f,rep = read_eam("CuAu_Zhou.eam.alloy",kind="eam/alloy") source1,parameters1,F1,f1,rep1 = mix_eam(["Cu_Zhou.eam.alloy","Au_Zhou.eam.alloy"],"eam/alloy","weight") write_eam(source1,parameters1,F1,f1,rep1,"CuAu_mixed.eam.alloy",kind="eam/alloy") calc0 = EAM('CuAu_Zhou.eam.alloy') calc1 = EAM('CuAu_mixed.eam.alloy') a = FaceCenteredCubic('Cu', size=[2,2,2]) a.set_calculator(calc0) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = FaceCenteredCubic('Cu', size=[2,2,2]) a.set_calculator(calc1) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) a = FaceCenteredCubic('Au', size=[2,2,2]) a.set_calculator(calc0) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = FaceCenteredCubic('Au', size=[2,2,2]) a.set_calculator(calc1) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) a = L1_2(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc0) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = L1_2(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc1) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) a = L1_2(['Cu', 'Au'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc0) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = L1_2(['Cu', 'Au'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc1) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) a = B1(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc0) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = B1(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc1) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) os.remove("CuAu_mixed.eam.alloy") ### if __name__ == '__main__': unittest.main()
8,520
40.364078
116
py
matscipy
matscipy-master/tests/test_hessian_finite_differences.py
# # Copyright 2020-2021 Lars Pastewka (U. Freiburg) # 2020 Jan Griesser (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import random import unittest import sys import numpy as np from numpy.linalg import norm import ase.io as io from ase.constraints import StrainFilter, UnitCellFilter from ase.lattice.compounds import B1, B2, L1_0, L1_2 from ase.lattice.cubic import FaceCenteredCubic from ase.optimize import FIRE from ase.units import GPa from ase.build import bulk import matscipytest from matscipy.calculators.pair_potential import PairPotential, LennardJonesCut import matscipy.calculators.pair_potential as calculator from matscipy.numerical import numerical_hessian ### class TestPairPotentialCalculator(matscipytest.MatSciPyTestCase): tol = 1e-4 def test_hessian_sparse(self): for calc in [{(1, 1): LennardJonesCut(1, 1, 3)}]: atoms = FaceCenteredCubic( 'H', size=[2, 2, 2], latticeconstant=1.550) a = calculator.PairPotential(calc) atoms.calc = a H_analytical = a.get_hessian(atoms, "sparse") H_numerical = numerical_hessian(atoms, d=1e-5, indices=None) self.assertArrayAlmostEqual( H_analytical.todense(), H_numerical.todense(), tol=self.tol) def test_symmetry_sparse(self): for calc in [{(1, 1): LennardJonesCut(1, 1, 3)}]: atoms = FaceCenteredCubic( 'H', size=[2, 2, 2], latticeconstant=1.550) a = calculator.PairPotential(calc) atoms.calc = a H_numerical = numerical_hessian(atoms, d=1e-5, indices=None) H_numerical = H_numerical.todense() self.assertArrayAlmostEqual( np.sum(np.abs(H_numerical - H_numerical.T)), 0, tol=1e-5) def test_hessian_sparse_split(self): for calc in [{(1, 1): LennardJonesCut(1, 1, 3)}]: atoms = FaceCenteredCubic( 'H', size=[2, 2, 2], latticeconstant=1.550) nat = len(atoms) a = calculator.PairPotential(calc) atoms.calc = a H_analytical = a.get_hessian(atoms, "sparse") H_numerical_split1 = numerical_hessian( atoms, d=1e-5, indices=np.arange(0, np.int32(nat / 2), 1)) H_numerical_split2 = numerical_hessian( atoms, d=1e-5, indices=np.arange(np.int32(nat / 2), nat, 1)) H_numerical_splitted = np.concatenate( (H_numerical_split1.todense(), H_numerical_split2.todense()), axis=0) self.assertArrayAlmostEqual( H_analytical.todense(), H_numerical_splitted, tol=self.tol) ### if __name__ == '__main__': unittest.main()
4,439
37.608696
78
py
matscipy
matscipy-master/tests/test_spatial_correlation_function.py
# # Copyright 2016, 2020-2021 Lars Pastewka (U. Freiburg) # 2016 Richard Jana (KIT & U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np from matscipy.neighbours import neighbour_list from ase import Atoms import matscipytest from matscipy.spatial_correlation_function import spatial_correlation_function import ase.io as io #import matplotlib.pyplot as plt class TestSpatialCorrelationFunction(unittest.TestCase): def test_radial_distribution_function(self): # Radial distribution function is obtained for correlations of unity. # This is not a particularly good test. # Tilt unit cell to check results for non-orthogonal cells. for i in range(-1,2): a = io.read('aC.cfg') a1, a2, a3 = a.cell a3[0] += i*a1[0] a.set_cell([a1, a2, a3]) a.set_scaled_positions(a.get_scaled_positions()) v = np.ones(len(a)) SCF1, r1 = spatial_correlation_function(a, v, 10.0, 0.1, 8.0, 0.1, norm=False) SCF2, r2 = spatial_correlation_function(a, v, 10.0, 0.1, 2.0, 0.1, norm=False) #print(np.abs(SCF1-SCF2).max()) #print(r1[np.argmax(np.abs(SCF1-SCF2))]) #plt.plot(r1, SCF1, label='$8$') #plt.plot(r2, SCF2, label='$2$') #plt.legend(loc='best') #plt.show() self.assertTrue(np.abs(SCF1-SCF2).max() < 0.31) # def test_peak_count(self): # n=50 # # xyz=np.zeros((n,3)) # xyz[:,0]=np.arange(n) # values=np.random.rand(len(xyz)) # # atoms=Atoms(positions=xyz, cell=np.array([[n,0,0],[0,n,0],[0,0,n]])) # # length_cutoff= n/2. # output_gridsize= 0.1 # FFT_cutoff= 7.5 # approx_FFT_gridsize= 1. # SCF, r=spatial_correlation_function(atoms, values, length_cutoff, output_gridsize, FFT_cutoff, approx_FFT_gridsize,dim=None,delta='simple',norm=True) # SCF2, r2=spatial_correlation_function(atoms, values, length_cutoff, output_gridsize, FFT_cutoff, approx_FFT_gridsize/50.*n,dim=None,delta='simple',norm=True) # SCF3, r3=spatial_correlation_function(atoms, values, length_cutoff, output_gridsize, FFT_cutoff, approx_FFT_gridsize/20.*n,dim=None,delta='simple',norm=True) # # SCF-=SCF.min() # SCF2-=SCF2.min() # SCF3-=SCF3.min() # # self.assertAlmostEqual(np.isfinite(SCF/SCF).sum(), np.floor(length_cutoff)) # self.assertAlmostEqual(np.isfinite(SCF2/SCF2).sum(), int(np.floor(FFT_cutoff)+np.ceil(np.ceil(length_cutoff-FFT_cutoff)*50./n))) # self.assertAlmostEqual(np.isfinite(SCF3/SCF3).sum(), int(np.floor(FFT_cutoff)+np.ceil(np.ceil(length_cutoff-FFT_cutoff)*20./n))) def test_directional_spacing(self): n=30 xyz=np.zeros((n**3,3)) m=np.meshgrid(np.arange(0,n,1),np.arange(0,2*n,2),np.arange(0,3*n,3)) xyz[:,0]=m[0].reshape((-1)) xyz[:,1]=m[0].reshape((-1)) xyz[:,2]=m[2].reshape((-1)) values=np.random.rand(len(xyz)) atoms=Atoms(positions=xyz, cell=np.array([[n,0,0],[0,2*n,0],[0,0,3*n]])) length_cutoff= n output_gridsize= 0.1 FFT_cutoff= 0. approx_FFT_gridsize= 1. SCF0, r0=spatial_correlation_function(atoms, values, length_cutoff, output_gridsize, FFT_cutoff, approx_FFT_gridsize, dim=0, delta='simple', norm=True) SCF1, r1=spatial_correlation_function(atoms, values, length_cutoff, output_gridsize, FFT_cutoff, approx_FFT_gridsize, dim=1, delta='simple', norm=True) SCF2, r2=spatial_correlation_function(atoms, values, length_cutoff, output_gridsize, FFT_cutoff, approx_FFT_gridsize, dim=2, delta='simple', norm=True) SCF0-=SCF0.min() SCF1-=SCF1.min() SCF2-=SCF2.min() n_peaks0=np.isfinite(SCF0/SCF0).sum() n_peaks1=np.isfinite(SCF1/SCF1).sum() n_peaks2=np.isfinite(SCF2/SCF2).sum() self.assertTrue(n_peaks0/2.-n_peaks1 < 2) self.assertTrue(n_peaks0/3.-n_peaks2 < 2) ### if __name__ == '__main__': unittest.main()
5,889
40.77305
166
py
matscipy
matscipy-master/tests/test_mcfm.py
# # Copyright 2020-2021 Lars Pastewka (U. Freiburg) # 2018 Jacek Golebiowski (Imperial College London) # 2018 [email protected] # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import numpy as np import ase.io from math import exp, sqrt from ase.calculators.calculator import Calculator from matscipy.calculators.mcfm.neighbour_list_mcfm.neighbour_list_mcfm import NeighbourListMCFM from matscipy.calculators.mcfm.qm_cluster import QMCluster from matscipy.calculators.mcfm.calculator import MultiClusterForceMixingPotential import unittest import matscipytest ### clustering_ckeck = [[9, 10, 11, 12, 13, 14, 15, 16, 17, 19]] clustering_marks_check = np.array([2, 3, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 2, 2, 2, 2, 2, 3, 0, 3, 0]) neighbour_list_check = [ np.array([4, 2, 1], dtype=int), np.array([0], dtype=int), np.array([0], dtype=int), np.array([7, 4, 5], dtype=int), np.array([3, 0], dtype=int), np.array([3], dtype=int), np.array([10, 7, 8], dtype=int), np.array([6, 3], dtype=int), np.array([6], dtype=int), np.array([13, 11, 10], dtype=int), np.array([9, 6], dtype=int), np.array([9], dtype=int), np.array([16, 13, 14], dtype=int), np.array([12, 9], dtype=int), np.array([12], dtype=int), np.array([19, 17, 16], dtype=int), np.array([15, 12], dtype=int), np.array([15], dtype=int), np.array([20, 22, 19], dtype=int), np.array([18, 15], dtype=int), np.array([18], dtype=int), np.array([25, 23, 22], dtype=int), np.array([21, 18], dtype=int), np.array([21], dtype=int), np.array([28, 26, 25], dtype=int), np.array([24, 21], dtype=int), np.array([24], dtype=int), np.array([29, 28], dtype=int), np.array([27, 24], dtype=int), np.array([27], dtype=int), ] def load_atoms(filename): """Load atoms from the file""" atoms = ase.io.read(filename, index=0, format="extxyz") atoms.arrays["atomic_index"] = np.arange(len(atoms)) return atoms def create_neighbour_list(atoms): """Create the neighbour list""" hysteretic_cutoff_break_factor = 3 cutoffs = dict() c_helper = dict(H=0.7, C=1, N=1, O=1) for keyi in c_helper: for keyj in c_helper: cutoffs[(keyi, keyj)] = c_helper[keyi] + c_helper[keyj] neighbour_list = NeighbourListMCFM(atoms, cutoffs, skin=0.3, hysteretic_break_factor=hysteretic_cutoff_break_factor) neighbour_list.update(atoms) return neighbour_list class MorsePotentialPerAtom(Calculator): """Morse potential. Default values chosen to be similar as Lennard-Jones. """ implemented_properties = ['energy', 'forces', 'potential_energies'] default_parameters = {'epsilon': 1.0, 'rho0': 6.0, 'r0': 1.0} nolabel = True def __init__(self, **kwargs): Calculator.__init__(self, **kwargs) def calculate(self, atoms=None, properties=['energy'], system_changes=['positions', 'numbers', 'cell', 'pbc', 'charges', 'magmoms']): Calculator.calculate(self, atoms, properties, system_changes) epsilon = self.parameters.epsilon rho0 = self.parameters.rho0 r0 = self.parameters.r0 positions = self.atoms.get_positions() energy = 0.0 energies = np.zeros(len(self.atoms)) forces = np.zeros((len(self.atoms), 3)) preF = 2 * epsilon * rho0 / r0 for i1, p1 in enumerate(positions): for i2, p2 in enumerate(positions[:i1]): diff = p2 - p1 r = sqrt(np.dot(diff, diff)) expf = exp(rho0 * (1.0 - r / r0)) energy += epsilon * expf * (expf - 2) energies[i1] += epsilon * expf * (expf - 2) energies[i2] += epsilon * expf * (expf - 2) F = preF * expf * (expf - 1) * diff / r forces[i1] -= F forces[i2] += F self.results['energy'] = energy self.results['forces'] = forces self.results['potential_energies'] = energies def create_mcfm_potential(atoms, classical_calculator=None, qm_calculator=None, special_atoms_list=None, double_bonded_atoms_list=None ): """Set up a multi cluster force mixing potential with a sensible set of defaults Parameters ---------- atoms : ASE.atoms atoms object classical_calculator : AE.calculator classical calculator qm_calculator : ASE.calculator qm calculator special_atoms_list : list of ints (atomic indices) In case a group of special atoms are specified (special molecule), If one of these atoms is in the buffer region, the rest are also added to it. double_bonded_atoms_list : list list of doubly bonded atoms for the clustering module, needed for double hydrogenation. Returns ------- MultiClusterForceMixingPotential ase.calculator supporting hybrid simulations. """ if special_atoms_list is None: special_atoms_list = [[]] if double_bonded_atoms_list is None: double_bonded_atoms_list = [] # Stage 1 - Neighbour List routines neighbour_list = create_neighbour_list(atoms) # Stage 1 - Set up QM clusters qm_flag_potential_energies = np.ones((len(atoms), 2), dtype=float) * 100 atoms.arrays["qm_flag_potential_energies[in_out]"] = qm_flag_potential_energies.copy() qm_cluster = QMCluster(special_atoms_list=special_atoms_list, verbose=0) qm_cluster.attach_neighbour_list(neighbour_list) qm_cluster.attach_flagging_module(qm_flag_potential_energies=qm_flag_potential_energies, small_cluster_hops=3, only_heavy=False, ema_parameter=0.01, energy_cap=1000, energy_increase=1) qm_cluster.attach_clustering_module(double_bonded_atoms_list=double_bonded_atoms_list) # Stage 1 - Set Up the multi cluster force mixing potential mcfm_pot = MultiClusterForceMixingPotential(atoms=atoms, classical_calculator=classical_calculator, qm_calculator=qm_calculator, qm_cluster=qm_cluster, forced_qm_list=None, change_bonds=True, calculate_errors=False, calculation_always_required=False, buffer_hops=6, verbose=0, enable_check_state=True ) mcfm_pot.debug_qm = False mcfm_pot.conserve_momentum = False # ------ Parallel module makes this simple simulation extremely slow # ------ Due ot large overhead. Use only with QM potentials mcfm_pot.doParallel = False atoms.set_calculator(mcfm_pot) return mcfm_pot ############################################################################### # ------ Actual tests ############################################################################### class TestMCFM(matscipytest.MatSciPyTestCase): def prepare_data(self): self.atoms = load_atoms("carbon_chain.xyz") self.morse1 = MorsePotentialPerAtom(r0=2, epsilon=2, rho0=6) self.morse2 = MorsePotentialPerAtom(r0=2, epsilon=4, rho0=6) self.mcfm_pot = create_mcfm_potential(self.atoms, classical_calculator=self.morse1, qm_calculator=self.morse2, special_atoms_list=None, double_bonded_atoms_list=None) def test_neighbour_list(self): self.prepare_data() nl = create_neighbour_list(self.atoms) for idx in range(len(self.atoms)): self.assertTrue((neighbour_list_check[idx] == nl.neighbours[idx]).all()) def test_clustering(self): self.prepare_data() self.mcfm_pot.qm_cluster.flagging_module.qm_flag_potential_energies[12, :] *= -20 self.mcfm_pot.get_forces(self.atoms) clusters = self.mcfm_pot.cluster_list cluster_marks = self.mcfm_pot.cluster_data_list[0].mark self.assertTrue(list(cluster_marks) == list(clustering_marks_check)) for idx in range(len(clusters)): self.assertTrue(clusters[idx].sort() == clustering_ckeck[idx].sort()) def test_forces(self): self.prepare_data() self.mcfm_pot.qm_cluster.flagging_module.qm_flag_potential_energies[12, :] *= -20 f = self.mcfm_pot.get_forces(self.atoms) cluster = self.mcfm_pot.cluster_list[0] fm1 = self.morse1.get_forces(self.atoms) fm2 = self.morse2.get_forces(self.atoms) for idx in range(len(self.atoms)): if idx in cluster: self.assertArrayAlmostEqual(f[idx, :], fm2[idx, :]) else: self.assertArrayAlmostEqual(f[idx, :], fm1[idx, :]) ### if __name__ == '__main__': unittest.main() ###
10,557
35.787456
100
py
matscipy
matscipy-master/tests/test_pair_potential_calculator.py
# # Copyright 2018-2021 Jan Griesser (U. Freiburg) # 2014, 2020-2021 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import random import pytest import sys import numpy as np from numpy.linalg import norm from scipy.linalg import eigh import ase import ase.io as io import ase.constraints from ase.optimize import FIRE from ase.lattice.cubic import FaceCenteredCubic from matscipy.calculators.pair_potential import ( PairPotential, LennardJonesQuadratic, LennardJonesLinear, ) from matscipy.elasticity import ( fit_elastic_constants, full_3x3x3x3_to_Voigt_6x6, measure_triclinic_elastic_constants, nonaffine_elastic_contribution ) from matscipy.calculators.calculator import MatscipyCalculator from matscipy.numerical import ( numerical_forces, numerical_stress, numerical_hessian, numerical_nonaffine_forces, ) ### def measure_triclinic_elastic_constants_2nd(a, delta=0.001): r0 = a.positions.copy() cell = a.cell.copy() volume = a.get_volume() e0 = a.get_potential_energy() C = np.zeros((3, 3, 3, 3), dtype=float) for i in range(3): for j in range(3): a.set_cell(cell, scale_atoms=True) a.set_positions(r0) e = np.zeros((3, 3)) e[i, j] += 0.5*delta e[j, i] += 0.5*delta F = np.eye(3) + e a.set_cell(np.matmul(F, cell.T).T, scale_atoms=True) ep = a.get_potential_energy() e = np.zeros((3, 3)) e[i, j] -= 0.5*delta e[j, i] -= 0.5*delta F = np.eye(3) + e a.set_cell(np.matmul(F, cell.T).T, scale_atoms=True) em = a.get_potential_energy() C[:, :, i, j] = (ep + em - 2*e0) / (delta ** 2) a.set_cell(cell, scale_atoms=True) a.set_positions(r0) return C def test_forces(): """ Test the computation of forces for a crystal and a glass """ calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5)} atoms = FaceCenteredCubic('H', size=[2, 2, 2], latticeconstant=1.0) atoms.rattle(0.01) b = PairPotential(calc) atoms.calc = b f = atoms.get_forces() fn = numerical_forces(atoms, d=1e-5) np.testing.assert_allclose(f, fn, atol=1e-4) calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5), (1, 2): LennardJonesQuadratic(1.5, 0.8, 2.0), (2, 2): LennardJonesQuadratic(0.5, 0.88, 2.2)} atoms = io.read('glass_min.xyz') atoms.rattle(0.01) b = PairPotential(calc) atoms.calc = b f = atoms.get_forces() fn = numerical_forces(atoms, d=1e-5) np.testing.assert_allclose(f, fn, atol=1e-3, rtol=1e-4) @pytest.mark.parametrize('a0', [1.0, 1.5, 2.0, 2.5, 3.0]) def test_crystal_stress(a0): """ Test the computation of stresses for a crystal """ calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5)} atoms = FaceCenteredCubic('H', size=[2, 2, 2], latticeconstant=a0) b = PairPotential(calc) atoms.calc = b s = atoms.get_stress() sn = numerical_stress(atoms, d=1e-5) np.testing.assert_allclose(s, sn, atol=1e-4, rtol=1e-4) def test_amorphous_stress(): """ Test the computation of stresses for a glass """ calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5), (1, 2): LennardJonesQuadratic(1.5, 0.8, 2.0), (2, 2): LennardJonesQuadratic(0.5, 0.88, 2.2)} atoms = io.read('glass_min.xyz') b = PairPotential(calc) atoms.calc = b s = atoms.get_stress() sn = numerical_stress(atoms, d=1e-5) np.testing.assert_allclose(s, sn, atol=1e-4, rtol=1e-4) def test_hessian(): """ Test the computation of the Hessian matrix """ calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5), (1, 2): LennardJonesQuadratic(1.5, 0.8, 2.0), (2, 2): LennardJonesQuadratic(0.5, 0.88, 2.2)} atoms = io.read("glass_min.xyz") b = PairPotential(calc) atoms.calc = b FIRE(atoms, logfile=None).run(fmax=1e-5) H_numerical = numerical_hessian(atoms, d=1e-5, indices=None).todense() H_analytical = b.get_property('hessian', atoms).todense() np.testing.assert_allclose(H_analytical, H_numerical, atol=1e-4, rtol=1e-4) def test_symmetry_sparse(): """ Test the symmetry of the dense Hessian matrix """ calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5), (1, 2): LennardJonesQuadratic(1.5, 0.8, 2.0), (2, 2): LennardJonesQuadratic(0.5, 0.88, 2.2)} atoms = io.read('glass_min.xyz') b = PairPotential(calc) atoms.calc = b FIRE(atoms, logfile=None).run(fmax=1e-5) H = b.get_property('hessian', atoms).todense() np.testing.assert_allclose(np.sum(np.abs(H-H.T)), 0, atol=1e-10, rtol=1e-4) def test_hessian_divide_by_masses(): """ Test the computation of the Dynamical matrix """ calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5), (1, 2): LennardJonesQuadratic(1.5, 0.8, 2.0), (2, 2): LennardJonesQuadratic(0.5, 0.88, 2.2)} atoms = io.read("glass_min.xyz") b = PairPotential(calc) atoms.calc = b FIRE(atoms, logfile=None).run(fmax=1e-5) masses_n = np.random.randint(1, 10, size=len(atoms)) atoms.set_masses(masses=masses_n) D_analytical = b.get_property('dynamical_matrix', atoms).todense() H_analytical = b.get_property('hessian', atoms).todense() masses_p = masses_n.repeat(3) H_analytical /= np.sqrt(masses_p.reshape(-1, 1) * masses_p.reshape(1, -1)) np.testing.assert_allclose(H_analytical, D_analytical, atol=1e-4, rtol=1e-4) def test_non_affine_forces_glass(): """ Test the computation of the non-affine forces """ calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5), (1, 2): LennardJonesQuadratic(1.5, 0.8, 2.0), (2, 2): LennardJonesQuadratic(0.5, 0.88, 2.2)} atoms = io.read("glass_min.xyz") b = PairPotential(calc) atoms.calc = b FIRE(atoms, logfile=None).run(fmax=1e-5) naForces_num = numerical_nonaffine_forces(atoms, d=1e-5) naForces_ana = b.get_property('nonaffine_forces', atoms) np.testing.assert_allclose(naForces_num, naForces_ana, atol=0.1, rtol=1e-4) @pytest.mark.parametrize('a0', [1.0, 1.5, 2.0, 2.3]) def test_crystal_birch_elastic_constants(a0): """ Test the Birch elastic constants for a crystalline system """ calc = {(1, 1): LennardJonesLinear(1, 1, 2.5)} atoms = FaceCenteredCubic('H', size=[2, 2, 2], latticeconstant=a0) b = PairPotential(calc) atoms.calc = b FIRE(ase.constraints.UnitCellFilter(atoms, mask=[0, 0, 0, 1, 1, 1]), logfile=None).run(fmax=1e-5) C_num = measure_triclinic_elastic_constants(atoms, delta=1e-4) C_ana = b.get_property("birch_coefficients", atoms) np.testing.assert_allclose(C_num, C_ana, atol=1e-3, rtol=1e-4) def test_amorphous_birch_elastic_constants(): """ Test the Birch elastic constants for an amorphous system """ calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5), (1, 2): LennardJonesQuadratic(1.5, 0.8, 2.0), (2, 2): LennardJonesQuadratic(0.5, 0.88, 2.2)} atoms = io.read("glass_min.xyz") b = PairPotential(calc) atoms.calc = b FIRE(ase.constraints.UnitCellFilter(atoms, mask=[1, 1, 1, 1, 1, 1]), logfile=None).run(fmax=1e-5) C_num = measure_triclinic_elastic_constants(atoms, delta=1e-4) C_ana = b.get_property("birch_coefficients", atoms) np.testing.assert_allclose(C_num, C_ana, atol=1e-3, rtol=1e-4) @pytest.mark.parametrize('a0', [1.0, 1.5, 2.0, 2.3]) def test_non_affine_elastic_constants_crystal(a0): """ Test the computation of Birch elastic constants and correction due to non-affine displacements """ calc = {(1, 1): LennardJonesLinear(1, 1, 2.5)} atoms = FaceCenteredCubic('H', size=[3,3,3], latticeconstant=a0) b = PairPotential(calc) atoms.calc = b FIRE(ase.constraints.UnitCellFilter(atoms, mask=[0, 0, 0, 1, 1, 1]), logfile=None).run(fmax=1e-5) C_num = measure_triclinic_elastic_constants(atoms, delta=5e-4, optimizer=FIRE, fmax=1e-6, steps=500) C_ana = b.get_property("elastic_constants", atoms) np.testing.assert_allclose(np.where(C_ana < 1e-6, 0.0, C_ana), np.where(C_num < 1e-6, 0.0, C_num), rtol=1e-3, atol=1e-3) def test_non_affine_elastic_constants_glass(): """ Test the computation of Birch elastic constants and correction due to non-affine displacements """ calc = {(1, 1): LennardJonesQuadratic(1, 1, 2.5), (1, 2): LennardJonesQuadratic(1.5, 0.8, 2.0), (2, 2): LennardJonesQuadratic(0.5, 0.88, 2.2)} atoms = io.read("glass_min.xyz") b = PairPotential(calc) atoms.calc = b FIRE(ase.constraints.UnitCellFilter(atoms, mask=[1, 1, 1, 1, 1, 1]), logfile=None).run(fmax=1e-5) C_num = measure_triclinic_elastic_constants(atoms, delta=5e-4, optimizer=FIRE, fmax=1e-6, steps=500) C_ana = b.get_property("elastic_constants", atoms) np.testing.assert_allclose(np.where(C_ana < 1e-6, 0.0, C_ana), np.where(C_num < 1e-6, 0.0, C_num), rtol=1e-3, atol=1e-3) H_nn = b.get_hessian(atoms, "sparse").todense() eigenvalues, eigenvectors = eigh(H_nn, subset_by_index=[3, 3*len(atoms)-1]) B_ana = b.get_property("birch_coefficients", atoms) B_ana += nonaffine_elastic_contribution(atoms, eigenvalues, eigenvectors) np.testing.assert_allclose(np.where(B_ana < 1e-6, 0.0, B_ana), np.where(C_num < 1e-6, 0.0, C_num), rtol=1e-3, atol=1e-3) def test_elastic_born_crystal_stress(): class TestPotential(): def __init__(self, cutoff): self.cutoff = cutoff def __call__(self, r): # Return function value (potential energy). return r - self.cutoff #return np.ones_like(r) def get_cutoff(self): return self.cutoff def first_derivative(self, r): return np.ones_like(r) #return np.zeros_like(r) def second_derivative(self, r): return np.zeros_like(r) def derivative(self, n=1): if n == 1: return self.first_derivative elif n == 2: return self.second_derivative else: raise ValueError( "Don't know how to compute {}-th derivative.".format(n)) for calc in [{(1, 1): LennardJonesQuadratic(1.0, 1.0, 2.5)}]: #for calc in [{(1, 1): TestPotential(2.5)}]: b = PairPotential(calc) atoms = FaceCenteredCubic('H', size=[6,6,6], latticeconstant=1.2) # Randomly deform the cell strain = np.random.random([3, 3]) * 0.02 atoms.set_cell(np.matmul(np.identity(3) + strain, atoms.cell), scale_atoms=True) atoms.calc = b FIRE(ase.constraints.StrainFilter(atoms, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=1e-5) Cnum, Cerr_num = fit_elastic_constants(atoms, symmetry="triclinic", N_steps=11, delta=1e-4, optimizer=None, verbose=False) Cnum2_voigt = full_3x3x3x3_to_Voigt_6x6(measure_triclinic_elastic_constants(atoms), tol=10) #Cnum3_voigt = full_3x3x3x3_to_Voigt_6x6(measure_triclinic_elastic_constants_2nd(atoms), tol=10) Cana = b.get_birch_coefficients(atoms) Cana_voigt = full_3x3x3x3_to_Voigt_6x6(Cana, tol=10) #print(atoms.get_stress()) #print(Cnum) #print(Cana_voigt) np.set_printoptions(precision=3) #print("Stress: \n", atoms.get_stress()) #print("Numeric (fit_elastic_constants): \n", Cnum) #print("Numeric (measure_triclinic_elastic_constants): \n", Cnum2_voigt) #print("Numeric (measure_triclinic_elastic_constants_2nd): \n", Cnum3_voigt) #print("Analytic: \n", Cana_voigt) #print("Absolute Difference (fit_elastic_constants): \n", Cnum-Cana_voigt) #print("Absolute Difference (measure_triclinic_elastic_constants): \n", Cnum2_voigt-Cana_voigt) #print("Difference between numeric results: \n", Cnum-Cnum2_voigt) np.testing.assert_allclose(Cnum, Cana_voigt, atol=10)
14,029
38.08078
130
py
matscipy
matscipy-master/tests/test_energy_release.py
# # Copyright 2014-2015, 2020-2021 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import math import pytest import numpy as np import ase.io from ase.constraints import FixAtoms from ase.optimize import FIRE import matscipy.fracture_mechanics.clusters as clusters from matscipy.atomic_strain import atomic_strain from matscipy.elasticity import Voigt_6_to_full_3x3_stress from matscipy.fracture_mechanics.crack import CubicCrystalCrack from matscipy.fracture_mechanics.energy_release import J_integral from matscipy.neighbours import neighbour_list try: import atomistica except ImportError: atomistica = None @pytest.mark.skipif(atomistica is None, reason="Atomistica not available") def test_J_integral(): """ Check if the J-integral returns G=2*gamma """ nx = 128 for calc, a0, C11, C12, C44, surface_energy, bulk_coordination in [ ( atomistica.DoubleHarmonic( k1=1.0, r1=1.0, k2=1.0, r2=math.sqrt(2), cutoff=1.6 ), clusters.sc("He", 1.0, [nx, nx, 1], [1, 0, 0], [0, 1, 0]), 3, 1, 1, 0.05, 6, ), # ( atomistica.Harmonic(k=1.0, r0=1.0, cutoff=1.3, shift=False), # clusters.fcc('He', math.sqrt(2.0), [nx/2,nx/2,1], [1,0,0], # [0,1,0]), # math.sqrt(2), 1.0/math.sqrt(2), 1.0/math.sqrt(2), 0.05, 12) ]: print("{} atoms.".format(len(a0))) crack = CubicCrystalCrack( [1, 0, 0], [0, 1, 0], C11=C11, C12=C12, C44=C44 ) x, y, z = a0.positions.T r2 = min(np.max(x) - np.min(x), np.max(y) - np.min(y)) / 4 r1 = r2 / 2 a = a0.copy() a.center(vacuum=20.0, axis=0) a.center(vacuum=20.0, axis=1) ref = a.copy() r0 = ref.positions a.calc = calc print("epot = {}".format(a.get_potential_energy())) sx, sy, sz = a.cell.diagonal() tip_x = sx / 2 tip_y = sy / 2 k1g = crack.k1g(surface_energy) # g = a.get_array('groups') # groups are not defined g = np.ones(len(a)) # not fixing any atom old_x = tip_x + 1.0 old_y = tip_y + 1.0 while abs(tip_x - old_x) > 1e-6 and abs(tip_y - old_y) > 1e-6: a.set_constraint(None) ux, uy = crack.displacements(r0[:, 0], r0[:, 1], tip_x, tip_y, k1g) a.positions[:, 0] = r0[:, 0] + ux a.positions[:, 1] = r0[:, 1] + uy a.positions[:, 2] = r0[:, 2] a.set_constraint(ase.constraints.FixAtoms(mask=g == 0)) opt = FIRE(a, logfile=None) opt.run(fmax=1e-3) old_x = tip_x old_y = tip_y tip_x, tip_y = crack.crack_tip_position( a.positions[:, 0], a.positions[:, 1], r0[:, 0], r0[:, 1], tip_x, tip_y, k1g, mask=g != 0, ) print(tip_x, tip_y) # Get atomic strain i, j = neighbour_list("ij", a, cutoff=1.3) deformation_gradient, residual = atomic_strain( a, ref, neighbours=(i, j) ) # Get atomic stresses # Note: get_stresses returns the virial in Atomistica! virial = a.get_stresses() virial = Voigt_6_to_full_3x3_stress(virial) # Compute J-integral epot = a.get_potential_energies() eref = np.zeros_like(epot) for r1, r2 in [(r1, r2), (r1 / 2, r2 / 2), (r1 / 2, r2)]: print("r1 = {}, r2 = {}".format(r1, r2)) J = J_integral( a, deformation_gradient, virial, epot, eref, tip_x, tip_y, r1, r2, ) print("2*gamma = {0}, J = {1}".format(2 * surface_energy, J))
5,731
31.568182
83
py
matscipy
matscipy-master/tests/test_fit_elastic_constants.py
# # Copyright 2014, 2020 James Kermode (Warwick U.) # 2020 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import ase.io import ase.units as units from ase.constraints import StrainFilter from ase.lattice.cubic import Diamond from ase.optimize import FIRE try: import quippy.potential except ImportError: quippy = None import matscipytest from matscipy.elasticity import (fit_elastic_constants, measure_triclinic_elastic_constants) if quippy is not None: class TestFitElasticConstants(matscipytest.MatSciPyTestCase): """ Tests of elastic constant calculation. We test with a cubic Silicon lattice, since this also has most of the symmetries of the lower-symmetry crystal families """ def setUp(self): self.pot = quippy.potential.Potential('IP SW', param_str=""" <SW_params n_types="2" label="PRB_31_plus_H"> <comment> Stillinger and Weber, Phys. Rev. B 31 p 5262 (1984), extended for other elements </comment> <per_type_data type="1" atomic_num="1" /> <per_type_data type="2" atomic_num="14" /> <per_pair_data atnum_i="1" atnum_j="1" AA="0.0" BB="0.0" p="0" q="0" a="1.0" sigma="1.0" eps="0.0" /> <per_pair_data atnum_i="1" atnum_j="14" AA="8.581214" BB="0.0327827" p="4" q="0" a="1.25" sigma="2.537884" eps="2.1672" /> <per_pair_data atnum_i="14" atnum_j="14" AA="7.049556277" BB="0.6022245584" p="4" q="0" a="1.80" sigma="2.0951" eps="2.1675" /> <!-- triplet terms: atnum_c is the center atom, neighbours j and k --> <per_triplet_data atnum_c="1" atnum_j="1" atnum_k="1" lambda="21.0" gamma="1.20" eps="2.1675" /> <per_triplet_data atnum_c="1" atnum_j="1" atnum_k="14" lambda="21.0" gamma="1.20" eps="2.1675" /> <per_triplet_data atnum_c="1" atnum_j="14" atnum_k="14" lambda="21.0" gamma="1.20" eps="2.1675" /> <per_triplet_data atnum_c="14" atnum_j="1" atnum_k="1" lambda="21.0" gamma="1.20" eps="2.1675" /> <per_triplet_data atnum_c="14" atnum_j="1" atnum_k="14" lambda="21.0" gamma="1.20" eps="2.1675" /> <per_triplet_data atnum_c="14" atnum_j="14" atnum_k="14" lambda="21.0" gamma="1.20" eps="2.1675" /> </SW_params> """) self.fmax = 1e-4 self.at0 = Diamond('Si', latticeconstant=5.43) self.at0.set_calculator(self.pot) # relax initial positions and unit cell FIRE(StrainFilter(self.at0, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=self.fmax) self.C_ref = np.array([[ 151.4276439 , 76.57244456, 76.57244456, 0. , 0. , 0. ], [ 76.57244456, 151.4276439 , 76.57244456, 0. , 0. , 0. ], [ 76.57244456, 76.57244456, 151.4276439 , 0. , 0. , 0. ], [ 0. , 0. , 0. , 109.85498798, 0. , 0. ], [ 0. , 0. , 0. , 0. , 109.85498798, 0. ], [ 0. , 0. , 0. , 0. , 0. , 109.85498798]]) self.C_err_ref = np.array([[ 1.73091718, 1.63682097, 1.63682097, 0. , 0. , 0. ], [ 1.63682097, 1.73091718, 1.63682097, 0. , 0. , 0. ], [ 1.63682097, 1.63682097, 1.73091718, 0. , 0. , 0. ], [ 0. , 0. , 0. , 1.65751232, 0. , 0. ], [ 0. , 0. , 0. , 0. , 1.65751232, 0. ], [ 0. , 0. , 0. , 0. , 0. , 1.65751232]]) self.C_ref_relaxed = np.array([[ 151.28712587, 76.5394162 , 76.5394162 , 0. , 0. , 0. ], [ 76.5394162 , 151.28712587, 76.5394162 , 0. , 0. , 0. ], [ 76.5394162 , 76.5394162 , 151.28712587, 0. , 0. , 0. ], [ 0. , 0. , 0. , 56.32421772, 0. , 0. ], [ 0. , 0. , 0. , 0. , 56.32421772, 0. ], [ 0. , 0. , 0. , 0. , 0. , 56.32421772]]) self.C_err_ref_relaxed = np.array([[ 1.17748661, 1.33333615, 1.33333615, 0. , 0. , 0. ], [ 1.33333615, 1.17748661, 1.33333615, 0. , 0. , 0. ], [ 1.33333615, 1.33333615, 1.17748661, 0. , 0. , 0. ], [ 0. , 0. , 0. , 0.18959684, 0. , 0. ], [ 0. , 0. , 0. , 0. , 0.18959684, 0. ], [ 0. , 0. , 0. , 0. , 0. , 0.18959684]]) def test_measure_triclinic_unrelaxed(self): # compare to brute force method without relaxation C = measure_triclinic_elastic_constants(self.at0, delta=1e-2, optimizer=None) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref, tol=0.2) def test_measure_triclinic_relaxed(self): # compare to brute force method with relaxation C = measure_triclinic_elastic_constants(self.at0, delta=1e-2, optimizer=FIRE, fmax=self.fmax) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref_relaxed, tol=0.2) def testcubic_unrelaxed(self): C, C_err = fit_elastic_constants(self.at0, 'cubic', verbose=False, graphics=False) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref, tol=1e-2) if abs(C_err).max() > 0.: self.assertArrayAlmostEqual(C_err/units.GPa, self.C_err_ref, tol=1e-2) def testcubic_relaxed(self): C, C_err = fit_elastic_constants(self.at0, 'cubic', optimizer=FIRE, fmax=self.fmax, verbose=False, graphics=False) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref_relaxed, tol=1e-2) if abs(C_err).max() > 0.: self.assertArrayAlmostEqual(C_err/units.GPa, self.C_err_ref_relaxed, tol=1e-2) def testorthorhombic_unrelaxed(self): C, C_err = fit_elastic_constants(self.at0, 'orthorhombic', verbose=False, graphics=False) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref, tol=0.1) def testorthorhombic_relaxed(self): C, C_err = fit_elastic_constants(self.at0, 'orthorhombic', optimizer=FIRE, fmax=self.fmax, verbose=False, graphics=False) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref_relaxed, tol=0.1) def testmonoclinic_unrelaxed(self): C, C_err = fit_elastic_constants(self.at0, 'monoclinic', verbose=False, graphics=False) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref, tol=0.2) def testmonoclinic_relaxed(self): C, C_err = fit_elastic_constants(self.at0, 'monoclinic', optimizer=FIRE, fmax=self.fmax, verbose=False, graphics=False) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref_relaxed, tol=0.2) def testtriclinic_unrelaxed(self): C, C_err = fit_elastic_constants(self.at0, 'triclinic', verbose=False, graphics=False) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref, tol=0.2) def testtriclinic_relaxed(self): C, C_err = fit_elastic_constants(self.at0, 'triclinic', optimizer=FIRE, fmax=self.fmax, verbose=False, graphics=False) self.assertArrayAlmostEqual(C/units.GPa, self.C_ref_relaxed, tol=0.2) if __name__ == '__main__': unittest.main()
11,445
53.76555
126
py
matscipy
matscipy-master/tests/test_elastic_moduli.py
# # Copyright 2020-2021 Lars Pastewka (U. Freiburg) # 2015 [email protected] # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np from matscipy.elasticity import elastic_moduli ### def test_rotation(): Cs = [ np.array([ [165.7, 63.9, 63.9, 0, 0, 0], [63.9, 165.7, 63.9, 0, 0, 0], [63.9, 63.9, 165.7, 0, 0, 0], [0, 0, 0, 79.6, 0, 0], [0, 0, 0, 0, 79.6, 0], [0, 0, 0, 0, 0, 79.6], ]) ] l = [np.array([1, 0, 0]), np.array([1, 1, 0])] EM = [ {'E': np.array([130, 130, 130]), 'nu': np.array([0.28, 0.28, 0.28]), 'G': np.array([79.6, 79.6, 79.6])}, {'E': np.array([169, 169, 130]), 'nu': np.array([0.36, 0.28, 0.064]), 'G': np.array([79.6, 79.6, 50.9])} ] for C in Cs: for i, directions in enumerate(l): directions = directions / np.linalg.norm(directions) E, nu, Gm, B, K = elastic_moduli(C, l=directions) nu_v = np.array([nu[1, 2], nu[2, 0], nu[0, 1]]) G = np.array([Gm[1, 2], Gm[2, 0], Gm[0, 1]]) np.testing.assert_array_almost_equal(E, EM[i]['E'], decimal=1) np.testing.assert_array_almost_equal(nu_v, EM[i]['nu'], decimal=2) np.testing.assert_array_almost_equal(G, EM[i]['G'], decimal=9) def test_monoclinic(): C = np.array([ [5,2,2,0,1,0], [2,5,2,0,1,0], [2,2,5,0,1,0], [0,0,0,2,0,1], [1,1,1,0,2,0], [0,0,0,1,0,2] ]) l = [np.array([1, 0, 1]), np.array([1, 0, -1])] EM = np.array([5.4545,3.1579]) for i, directions in enumerate(l): directions = directions / np.linalg.norm(directions) E, nu, Gm, B, K = elastic_moduli(C, l=directions) np.testing.assert_almost_equal(E[0], EM[i], decimal=1) ### if __name__ == '__main__': unittest.main()
3,677
33.055556
78
py
matscipy
matscipy-master/tests/test_invariants.py
# # Copyright 2014, 2020-2021 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import matscipytest from matscipy.elasticity import invariants ### class TestInvariants(matscipytest.MatSciPyTestCase): def test_return_shape(self): sxx = np.array([[[10,11,12,13,14,15],[20,21,22,23,24,25]]], dtype=float) sxy = np.array([[[0,0,0,0,0,0],[0,0,0,0,0,0]]], dtype=float) P, tau, J3 = invariants(sxx, sxx, sxx, sxy, sxy, sxy) assert P.shape == sxx.shape assert tau.shape == sxx.shape assert J3.shape == sxx.shape assert np.abs(sxx+P).max() < 1e-12 ### if __name__ == '__main__': unittest.main()
2,451
34.536232
80
py
matscipy
matscipy-master/tests/test_full_to_Voigt.py
# # Copyright 2014, 2020-2021 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np from matscipy.elasticity import (full_3x3_to_Voigt_6_index, Voigt_6x6_to_full_3x3x3x3, full_3x3x3x3_to_Voigt_6x6, Voigt_6_to_full_3x3_strain, full_3x3_to_Voigt_6_strain, Voigt_6_to_full_3x3_stress, full_3x3_to_Voigt_6_stress) ### def test_full_3x3_to_Voigt_6_index(): assert full_3x3_to_Voigt_6_index(1, 1) == 1 assert full_3x3_to_Voigt_6_index(1, 2) == 3 assert full_3x3_to_Voigt_6_index(2, 1) == 3 assert full_3x3_to_Voigt_6_index(0, 2) == 4 assert full_3x3_to_Voigt_6_index(0, 1) == 5 def test_stiffness_conversion(): C6 = np.random.random((6, 6)) # Should be symmetric C6 = (C6 + C6.T) / 2 C3x3 = Voigt_6x6_to_full_3x3x3x3(C6) C6_check = full_3x3x3x3_to_Voigt_6x6(C3x3) np.testing.assert_array_almost_equal(C6, C6_check) def test_strain_conversion(): voigt0 = np.random.random(6) full1 = Voigt_6_to_full_3x3_strain(voigt0) voigt1 = full_3x3_to_Voigt_6_strain(full1) np.testing.assert_array_almost_equal(voigt0, voigt1) def test_stress_conversion(): voigt0 = np.random.random(6) full2 = Voigt_6_to_full_3x3_stress(voigt0) voigt2 = full_3x3_to_Voigt_6_stress(full2) np.testing.assert_array_almost_equal(voigt0, voigt2)
3,278
36.689655
72
py
matscipy
matscipy-master/tests/test_ffi.py
"""Testing that the compiled extension can be imported.""" def test_ffi(): import matscipy.ffi if __name__ == "__main__": test_ffi()
144
15.111111
58
py
matscipy
matscipy-master/tests/test_idealbrittlesolid.py
# # Copyright 2014-2015, 2017, 2020-2021 Lars Pastewka (U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import unittest import numpy as np import ase import ase.lattice.hexagonal import matscipytest from matscipy.fracture_mechanics.idealbrittlesolid import ( find_triangles_2d, IdealBrittleSolid, triangular_lattice_slab, ) from matscipy.numerical import numerical_forces, numerical_stress ### class TestNeighbours(matscipytest.MatSciPyTestCase): tol = 1e-6 def test_forces_and_virial(self): a = triangular_lattice_slab(1.0, 2, 2) calc = IdealBrittleSolid(rc=1.2, beta=0.0) a.set_calculator(calc) a.rattle(0.1) f = a.get_forces() fn = numerical_forces(a) self.assertArrayAlmostEqual(f, fn, tol=self.tol) self.assertArrayAlmostEqual(a.get_stress(), numerical_stress(a), tol=self.tol) def test_forces_linear(self): a = triangular_lattice_slab(1.0, 1, 1) calc = IdealBrittleSolid(rc=1.2, beta=0.0, linear=True) calc.set_reference_crystal(a) a.set_calculator(calc) a.rattle(0.01) f = a.get_forces() fn = numerical_forces(a) self.assertArrayAlmostEqual(f, fn, tol=self.tol) def test_two_triangles(self): a = ase.Atoms('4Xe', [[0,0,0], [1,0,0], [1,1,0], [0,1,0]]) a.center(vacuum=10) c1, c2, c3 = find_triangles_2d(a, 1.1) self.assertArrayAlmostEqual(np.transpose([c1, c2, c3]), [[0,1,2], [0,1,3], [0,2,3], [1,2,3]]) ### if __name__ == '__main__': unittest.main()
3,378
33.835052
101
py
matscipy
matscipy-master/tests/test_dislocation.py
# # Copyright 2018, 2020-2021 Petr Grigorev (Warwick U.) # 2020 James Kermode (Warwick U.) # 2019 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import os import unittest import matscipytest import sys import matscipy.dislocation as sd import numpy as np from ase.calculators.lammpslib import LAMMPSlib from matscipy.calculators.eam import EAM test_dir = os.path.dirname(os.path.realpath(__file__)) try: import matplotlib matplotlib.use("Agg") # Activate 'agg' backend for off-screen plotting for testing. except ImportError: print("matplotlib not found: skipping some tests") try: import lammps except ImportError: print("lammps not found: skipping some tests") try: import atomman except ImportError: print("atomman not found: skipping some tests") try: import ovito except ImportError: print("ovito not found: skipping some tests") class TestDislocation(matscipytest.MatSciPyTestCase): """Class to store test for dislocation.py module.""" @unittest.skipIf("atomman" not in sys.modules, 'requires Stroh solution from atomman to run') def test_core_position(self): """Make screw dislocation and fit a core position to it. Tests that the fitted core position is same as created """ print("Fitting the core, takes about 10 seconds") dft_alat = 3.19 dft_C11 = 488 dft_C12 = 200 dft_C44 = 137 dft_elastic_param = [dft_alat, dft_C11, dft_C12, dft_C44] cent_x = np.sqrt(6.0) * dft_alat / 3.0 center = np.array((cent_x, 0.0, 0.0)) # make the cell with dislocation core not in center disloc, bulk, u = sd.make_screw_cyl(dft_alat, dft_C11, dft_C12, dft_C44, cylinder_r=40, center=center) # initial guess is the center of the cell initial_guess = np.diagonal(disloc.cell).copy()[:2] / 2.0 core_pos = sd.fit_core_position(disloc, bulk, dft_elastic_param, origin=initial_guess, hard_core=False, core_radius=40) self.assertArrayAlmostEqual(core_pos, initial_guess + center[:2], tol=1e-4) def test_elastic_constants_EAM(self): """Test the get_elastic_constants() function using matscipy EAM calculator.""" target_values = np.array([3.1433, # alat 523.03, # C11 202.18, # C12 160.88]) # C44 for eam4 pot_name = "w_eam4.fs" pot_path = os.path.join(test_dir, pot_name) calc_EAM = EAM(pot_path) obtained_values = sd.get_elastic_constants(calculator=calc_EAM, delta=1.0e-3) self.assertArrayAlmostEqual(obtained_values, target_values, tol=1e-2) # This function tests the lammpslib and LAMMPS installation # skipped during automated testing @unittest.skipIf("lammps" not in sys.modules, "LAMMPS installation is required and thus is not good for automated testing") def test_elastic_constants_lammpslib(self): """Test the get_elastic_constants() function using lammpslib. If lammps crashes, check "lammps.log" file in the tests directory See lammps and ASE documentation on how to make lammpslib work """ print("WARNING: In case lammps crashes no error message is printed: ", "check 'lammps.log' file in test folder") target_values = np.array([3.1434, # alat 523.03, # C11 202.18, # C12 160.882]) # C44 for eam4 pot_name = "w_eam4.fs" pot_path = os.path.join(test_dir, pot_name) lammps = LAMMPSlib(lmpcmds=["pair_style eam/fs", "pair_coeff * * %s W" % pot_path], atom_types={'W': 1}, keep_alive=True, log_file="lammps.log") obtained_values = sd.get_elastic_constants(calculator=lammps, delta=1.0e-3) os.remove("lammps.log") self.assertArrayAlmostEqual(obtained_values, target_values, tol=1e-2) # This function tests the lammpslib and LAMMPS installation # skipped during automated testing @unittest.skipIf("lammps" not in sys.modules or "atomman" not in sys.modules, "LAMMPS installation and Stroh solution are required") def test_screw_cyl_lammpslib(self): """Test make_crew_cyl() and call lammpslib calculator. If lammps crashes, check "lammps.log" file in the tests directory See lammps and ASE documentation on how to make lammpslib work """ print("WARNING: In case lammps crashes no error message is printed: ", "check 'lammps.log' file in test folder") alat = 3.14339177996466 C11 = 523.0266819809012 C12 = 202.1786296941397 C44 = 160.88179872237012 cylinder_r = 40 cent_x = np.sqrt(6.0) * alat / 3.0 center = (cent_x, 0.0, 0.0) pot_name = "w_eam4.fs" pot_path = os.path.join(test_dir, pot_name) target_toten = -13086.484626 # Target value for w_eam4 lammps = LAMMPSlib(lmpcmds=["pair_style eam/fs", "pair_coeff * * %s W" % pot_path], atom_types={'W': 1}, keep_alive=True, log_file="lammps.log") disloc_ini, bulk_ini, __ = sd.make_screw_cyl(alat, C11, C12, C44, cylinder_r=cylinder_r, l_extend=center) disloc_ini.calc = lammps ini_toten = disloc_ini.get_potential_energy() self.assertAlmostEqual(ini_toten, target_toten, places=4) disloc_fin, __, __ = sd.make_screw_cyl(alat, C11, C12, C44, cylinder_r=cylinder_r, center=center) disloc_fin.calc = lammps fin_toten = disloc_fin.get_potential_energy() self.assertAlmostEqual(fin_toten, target_toten, places=4) os.remove("lammps.log") # Also requires version of atomman higher than 1.3.1.1 @unittest.skipIf("matplotlib" not in sys.modules or "atomman" not in sys.modules, "Requires matplotlib and atomman which is not a part of automated testing environment") def test_differential_displacement(self): """Test differential_displacement() function from atomman """ alat = 3.14339177996466 C11 = 523.0266819809012 C12 = 202.1786296941397 C44 = 160.88179872237012 cylinder_r = 40 cent_x = np.sqrt(6.0) * alat / 3.0 center = (cent_x, 0.0, 0.0) disloc_ini, bulk_ini, __ = sd.make_screw_cyl(alat, C11, C12, C44, cylinder_r=cylinder_r, l_extend=center) disloc_fin, __, __ = sd.make_screw_cyl(alat, C11, C12, C44, cylinder_r=cylinder_r, center=center) fig = sd.show_NEB_configurations([disloc_ini, disloc_fin], bulk_ini, xyscale=5.0, show=False) print("'dd_test.png' will be created: check the displacement map") fig.savefig("dd_test.png") @unittest.skipIf("atomman" not in sys.modules, 'requires Stroh solution from atomman to run') def test_read_dislo_QMMM(self): """Test read_dislo_QMMM() function""" alat = 3.14339177996466 C11 = 523.0266819809012 C12 = 202.1786296941397 C44 = 160.88179872237012 target_values = {"Nat": 1443, # total number of atoms "QM": 12, # number of atoms in QM region "MM": 876, # number of atoms in MM region "fixed": 555} # number of fixed atoms cylinder_r = 40 disloc, __, __ = sd.make_screw_cyl(alat, C11, C12, C44, cylinder_r=cylinder_r) x, y, _ = disloc.positions.T R = np.sqrt((x - x.mean()) ** 2 + (y - y.mean()) ** 2) R_cut = alat * np.sqrt(6.0) / 2.0 + 0.2 # radius for 12 QM atoms QM_mask = R < R_cut region = disloc.get_array("region") region[QM_mask] = np.full_like(region[QM_mask], "QM") disloc.set_array("region", region) disloc.write("test_read_dislo.xyz") test_disloc, __ = sd.read_dislo_QMMM("test_read_dislo.xyz") os.remove("test_read_dislo.xyz") Nat = len(test_disloc) self.assertEqual(Nat, target_values["Nat"]) total_Nat_type = 0 for atom_type in ["QM", "MM", "fixed"]: Nat_type = np.count_nonzero(region == atom_type) total_Nat_type += Nat_type self.assertEqual(Nat_type, target_values[atom_type]) # total number of atoms in region is equal to Nat (no atoms unmapped) self.assertEqual(Nat, total_Nat_type) # TODO # self.assertAtomsAlmostEqual(disloc, test_disloc) - # gives an error of _cell attribute new ase version? @unittest.skipIf("atomman" not in sys.modules, 'requires Stroh solution from atomman to run') def test_stroh_solution(self): """Builds isotropic Stroh solution and compares it to Volterra solution""" alat = 3.14 C11 = 523.0 C12 = 202.05 C44 = 160.49 # A = 2. * C44 / (C11 - C12) # print(A) # A = 0.999937 very isotropic material. # At values closer to 1.0 Stroh solution is numerically unstable # and does not pass checks cylinder_r = 40 burgers = alat * np.sqrt(3.0) / 2. __, W_bulk, u_stroh = sd.make_screw_cyl(alat, C11, C12, C44, cylinder_r=cylinder_r) x, y, __ = W_bulk.positions.T # make center of the cell at the dislocation core x -= x.mean() y -= y.mean() u_volterra = np.arctan2(y, x) * burgers / (2.0 * np.pi) # compare x and y components with zeros - isotropic solution self.assertArrayAlmostEqual(np.zeros_like(u_volterra), u_stroh[:, 0], tol=1e-4) self.assertArrayAlmostEqual(np.zeros_like(u_volterra), u_stroh[:, 1], tol=1e-4) # compare z component with simple Volterra solution self.assertArrayAlmostEqual(u_volterra, u_stroh[:, 2]) def test_make_screw_quadrupole_kink(self): """Test the total number of atoms in the quadrupole double kink configuration""" alat = 3.14 n1u = 5 kink_length = 20 kink, _, _ = sd.make_screw_quadrupole_kink(alat=alat, n1u=n1u, kink_length=kink_length) quadrupole_base, _, _, _ = sd.make_screw_quadrupole(alat=alat, n1u=n1u) self.assertEqual(len(kink), len(quadrupole_base) * 2 * kink_length) @unittest.skipIf("atomman" not in sys.modules, 'requires Stroh solution from atomman to run') def test_make_screw_cyl_kink(self): """Test the total number of atoms and number of fixed atoms in the cylinder double kink configuration""" alat = 3.14339177996466 C11 = 523.0266819809012 C12 = 202.1786296941397 C44 = 160.88179872237012 cent_x = np.sqrt(6.0) * alat / 3.0 center = [cent_x, 0.0, 0.0] cylinder_r = 40 kink_length = 26 (kink, large_disloc, _) = sd.make_screw_cyl_kink(alat, C11, C12, C44, kink_length=kink_length, cylinder_r=cylinder_r, kind="double") # check the total number of atoms as compared to make_screw_cyl() disloc, _, _ = sd.make_screw_cyl(alat, C11, C12, C12, cylinder_r=cylinder_r, l_extend=center) self.assertEqual(len(kink), len(disloc) * 2 * kink_length) kink_fixed_atoms = kink.constraints[0].get_indices() reference_fixed_atoms = kink.constraints[0].get_indices() # check that the same number of atoms is fixed self.assertEqual(len(kink_fixed_atoms), len(reference_fixed_atoms)) # check that the fixed atoms are the same and with same positions self.assertArrayAlmostEqual(kink_fixed_atoms, reference_fixed_atoms) self.assertArrayAlmostEqual(kink.positions[kink_fixed_atoms], large_disloc.positions[reference_fixed_atoms]) def test_slice_long_dislo(self): """Function to test slicing tool""" alat = 3.14339177996466 b = np.sqrt(3.0) * alat / 2.0 n1u = 5 kink_length = 20 kink, _, kink_bulk = sd.make_screw_quadrupole_kink(alat=alat, n1u=n1u, kink_length=kink_length) quadrupole_base, _, _, _ = sd.make_screw_quadrupole(alat=alat, n1u=n1u) sliced_kink, core_positions = sd.slice_long_dislo(kink, kink_bulk, b) # check the number of sliced configurations is equal # to length of 2 * kink_length * 3 (for double kink) self.assertEqual(len(sliced_kink), kink_length * 3 * 2) # check that the bulk and kink slices are the same size bulk_sizes = [len(slice[0]) for slice in sliced_kink] kink_sizes = [len(slice[1]) for slice in sliced_kink] self.assertArrayAlmostEqual(bulk_sizes, kink_sizes) # check that the size of slices are the same as single b configuration self.assertArrayAlmostEqual(len(quadrupole_base), len(sliced_kink[0][0])) (right_kink, _, kink_bulk) = sd.make_screw_quadrupole_kink(alat=alat, n1u=n1u, kind="right", kink_length=kink_length) sliced_right_kink, _ = sd.slice_long_dislo(right_kink, kink_bulk, b) # check the number of sliced configurations is equal # to length of kink_length * 3 - 2 (for right kink) self.assertEqual(len(sliced_right_kink), kink_length * 3 - 2) (left_kink, _, kink_bulk) = sd.make_screw_quadrupole_kink(alat=alat, n1u=n1u, kind="left", kink_length=kink_length) sliced_left_kink, _ = sd.slice_long_dislo(left_kink, kink_bulk, b) # check the number of sliced configurations is equal # to length of kink_length * 3 - 1 (for left kink) self.assertEqual(len(sliced_left_kink), kink_length * 3 - 1) def check_disloc(self, cls, ref_angle, structure="BCC", test_u=True, burgers=0.5 * np.array([1.0, 1.0, 1.0]), tol=10.0): alat = 3.14339177996466 C11 = 523.0266819809012 C12 = 202.1786296941397 C44 = 160.88179872237012 d = cls(alat, C11, C12, C44, symbol="Al") bulk, disloc = d.build_cylinder(20.0) # test that assigning non default symbol worked assert np.unique(bulk.get_chemical_symbols()) == "Al" assert np.unique(disloc.get_chemical_symbols()) == "Al" assert len(bulk) == len(disloc) if test_u: # test the consistency # displacement = disloc.positions - bulk.positions stroh_displacement = d.displacements(bulk.positions, np.diag(bulk.cell) / 2.0, self_consistent=d.self_consistent) displacement = disloc.positions - bulk.positions np.testing.assert_array_almost_equal(displacement, stroh_displacement) results = sd.ovito_dxa_straight_dislo_info(disloc, structure=structure) assert len(results) == 1 position, b, line, angle = results[0] self.assertArrayAlmostEqual(np.abs(b), burgers) # signs can change err = angle - ref_angle print(f'angle = {angle} ref_angle = {ref_angle} err = {err}') assert abs(err) < tol @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_screw_dislocation(self): self.check_disloc(sd.BCCScrew111Dislocation, 0.0) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_edge_dislocation(self): self.check_disloc(sd.BCCEdge111Dislocation, 90.0) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_edge100_dislocation(self,): self.check_disloc(sd.BCCEdge100Dislocation, 90.0, burgers=np.array([1.0, 0.0, 0.0])) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_edge100110_dislocation(self,): self.check_disloc(sd.BCCEdge100110Dislocation, 90.0, burgers=np.array([1.0, 0.0, 0.0])) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_mixed_dislocation(self): self.check_disloc(sd.BCCMixed111Dislocation, 70.5) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_30degree_diamond_partial_dislocation(self,): self.check_disloc(sd.DiamondGlide30degreePartial, 30.0, structure="Diamond", burgers=(1.0 / 6.0) * np.array([1.0, 2.0, 1.0])) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_90degree_diamond_partial_dislocation(self,): self.check_disloc(sd.DiamondGlide90degreePartial, 90.0, structure="Diamond", burgers=(1.0 / 6.0) * np.array([2.0, 1.0, 1.0])) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_screw_diamond_dislocation(self,): self.check_disloc(sd.DiamondGlideScrew, 0.0, structure="Diamond", burgers=(1.0 / 2.0) * np.array([0.0, 1.0, 1.0])) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_60degree_diamond_dislocation(self,): self.check_disloc(sd.DiamondGlide60Degree, 60.0, structure="Diamond", burgers=(1.0 / 2.0) * np.array([1.0, 0.0, 1.0])) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_fcc_screw_shockley_partial_dislocation(self,): self.check_disloc(sd.FCCScrewShockleyPartial, 30.0, structure="FCC", burgers=(1.0 / 6.0) * np.array([1.0, 2.0, 1.0])) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_fcc_screw110_dislocation(self,): self.check_disloc(sd.FCCScrew110Dislocation, 0.0, structure="FCC", burgers=(1.0 / 2.0) * np.array([0.0, 1.0, 1.0])) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_fcc_edge_shockley_partial_dislocation(self,): self.check_disloc(sd.FCCEdgeShockleyPartial, 60.0, structure="FCC", burgers=(1.0 / 6.0) * np.array([1.0, 2.0, 1.0])) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_fcc_edge110_partial_dislocation(self,): self.check_disloc(sd.FCCEdge110Dislocation, 90.0, structure="FCC", burgers=(1.0 / 2.0) * np.array([1.0, 1.0, 0.0])) def check_glide_configs(self, cls, structure="BCC"): alat = 3.14339177996466 C11 = 523.0266819809012 C12 = 202.1786296941397 C44 = 160.88179872237012 d = cls(alat, C11, C12, C44) bulk, disloc_ini, disloc_fin = d.build_glide_configurations(radius=40) assert len(bulk) == len(disloc_ini) assert len(disloc_ini) == len(disloc_fin) assert all(disloc_ini.get_array("fix_mask") == disloc_fin.get_array("fix_mask")) results = sd.ovito_dxa_straight_dislo_info(disloc_ini, structure=structure) assert len(results) == 1 ini_x_position = results[0][0][0] results = sd.ovito_dxa_straight_dislo_info(disloc_fin, structure=structure) assert len(results) == 1 fin_x_position = results[0][0][0] # test that difference between initial and final positions are # roughly equal to glide distance. # Since the configurations are unrelaxed dxa gives # a very rough estimation (especially for edge dislocations) # thus tolerance is taken to be ~1 Angstrom np.testing.assert_almost_equal(fin_x_position - ini_x_position, d.glide_distance, decimal=0) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_screw_glide(self): self.check_glide_configs(sd.BCCScrew111Dislocation) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_edge_glide(self): self.check_glide_configs(sd.BCCEdge111Dislocation) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_mixed_glide(self): self.check_glide_configs(sd.BCCMixed111Dislocation) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_edge100_glide(self): self.check_glide_configs(sd.BCCEdge100Dislocation) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_edge100110_glide(self): self.check_glide_configs(sd.BCCEdge100110Dislocation) @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_30degree_diamond_partial_glide(self): self.check_glide_configs(sd.DiamondGlide30degreePartial, structure="Diamond") @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_90degree_diamond_partial_glide(self): self.check_glide_configs(sd.DiamondGlide90degreePartial, structure="Diamond") @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_screw_diamond_glide(self): self.check_glide_configs(sd.DiamondGlideScrew, structure="Diamond") @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_60degree_diamond_glide(self): self.check_glide_configs(sd.DiamondGlide60Degree, structure="Diamond") @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_fcc_screw_shockley_partial_glide(self): self.check_glide_configs(sd.FCCScrewShockleyPartial, structure="FCC") @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_fcc_screw_110_glide(self): self.check_glide_configs(sd.FCCScrew110Dislocation, structure="FCC") @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_fcc_edge_shockley_partial_glide(self): self.check_glide_configs(sd.FCCEdgeShockleyPartial, structure="FCC") @unittest.skipIf("atomman" not in sys.modules or "ovito" not in sys.modules, "requires atomman and ovito") def test_fcc_edge_dislocation_glide(self): self.check_glide_configs(sd.FCCEdge110Dislocation, structure="FCC") def test_fixed_line_atoms(self): from ase.build import bulk pot_name = "w_eam4.fs" pot_path = os.path.join(test_dir, pot_name) calc_EAM = EAM(pot_path) # slightly pressurised cell to avoid exactly zero forces W = bulk("W", a=0.9 * 3.143392, cubic=True) W = W * [2, 2, 2] del W[0] W.calc = calc_EAM for line_direction in [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]: fixed_mask = W.positions.T[0] > W.cell[0, 0] / 2.0 - 0.1 W.set_constraint(sd.FixedLineAtoms(fixed_mask, line_direction)) line_dir_mask = np.array(line_direction, dtype=bool) # forces in direction other than line dir are zero assert (W.get_forces()[fixed_mask].T[~line_dir_mask] == 0.0).all() # forces in line direction are non zero assert (W.get_forces()[fixed_mask].T[line_dir_mask] != 0.0).all() # forces on unconstrained atoms are non zero assert (W.get_forces()[~fixed_mask] != 0.0).all() @unittest.skipIf("lammps" not in sys.modules, "LAMMPS installation is required and " + "thus is not good for automated testing") def test_gamma_line(self): # eam_4 parameters eam4_elastic_param = 3.143392, 527.025604, 206.34803, 165.092165 dislocation = sd.BCCEdge111Dislocation(*eam4_elastic_param) unit_cell = dislocation.unit_cell pot_name = "w_eam4.fs" pot_path = os.path.join(test_dir, pot_name) # calc_EAM = EAM(pot_name) eam calculator is way too slow lammps = LAMMPSlib(lmpcmds=["pair_style eam/fs", "pair_coeff * * %s W" % pot_path], atom_types={'W': 1}, keep_alive=True, log_file="lammps.log") unit_cell.calc = lammps shift, E = sd.gamma_line(unit_cell, surface=1, factor=5) # target values corresponding to fig 2(a) of # J.Phys.: Condens.Matter 25(2013) 395502 # http://iopscience.iop.org/0953-8984/25/39/395502 target_E = [0.00000000e+00, 1.57258669e-02, 5.31974533e-02, 8.01241031e-02, 9.37911067e-02, 9.54010452e-02, 9.37911067e-02, 8.01241032e-02, 5.31974533e-02, 1.57258664e-02, 4.33907234e-14] target_shift = [0., 0.27222571, 0.54445143, 0.81667714, 1.08890285, 1.36112857, 1.63335428, 1.90557999, 2.17780571, 2.45003142, 2.72225714] np.testing.assert_almost_equal(E, target_E, decimal=3) np.testing.assert_almost_equal(shift, target_shift, decimal=3) if __name__ == '__main__': unittest.main()
30,701
40.658073
108
py
matscipy
matscipy-master/tests/test_c2d.py
# # Copyright 2021 Lars Pastewka (U. Freiburg) # 2019-2021 Johannes Hoermann (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # import ase.io import io import matscipytest import numpy as np import os, os.path import shutil import stat import subprocess import tempfile import unittest from distutils.version import LooseVersion class c2dCliTest(matscipytest.MatSciPyTestCase): """Tests c2d and pnp command line interfaces""" def setUp(self): """Reads reference data files""" self.test_path = os.path.dirname(os.path.abspath(__file__)) self.data_path = os.path.join(self.test_path, 'electrochemistry_data') # Provides 0.1 mM NaCl solution at 0.05 V across 100 nm cell reference # data from binary npz file self.ref_npz = np.load( os.path.join(self.data_path,'NaCl.npz') ) # Provides 0.1 mM NaCl solution at 0.05 V across 100 nm cell reference # data from plain text file self.ref_txt = np.loadtxt(os.path.join(self.data_path,'NaCl.txt'), unpack=True) # Provides 0.1 mM NaCl (15 Na, 15 Cl) solution at 0.05 V across # [50,50,100] nm box reference sample from xyz file self.ref_xyz = ase.io.read(os.path.join(self.data_path,'NaCl.xyz')) # Provides 0.1 mM NaCl (15 Na, 15 Cl) solution at 0.05 V across # [50,50,100] nm box reference sample from LAMMPS data file self.ref_lammps = ase.io.read( os.path.join(self.data_path,'NaCl.lammps'),format='lammps-data') # command line interface scripts are expected to reside within # ../matscipy/cli/electrochemistry relative to this test directory self.pnp_cli = os.path.join( self.test_path,os.path.pardir,'matscipy','cli','electrochemistry','pnp.py') self.c2d_cli = os.path.join( self.test_path,os.path.pardir,'matscipy','cli','electrochemistry','c2d.py') self.assertTrue(os.path.exists(self.pnp_cli)) self.assertTrue(os.path.exists(self.c2d_cli)) self.bin_path = tempfile.TemporaryDirectory() # mock callable executables on path: pnp_exe = os.path.join(self.bin_path.name,'pnp') c2d_exe = os.path.join(self.bin_path.name,'c2d') shutil.copyfile(self.pnp_cli,pnp_exe) shutil.copyfile(self.c2d_cli,c2d_exe) st = os.stat(pnp_exe) os.chmod(pnp_exe, st.st_mode | stat.S_IEXEC) st = os.stat(c2d_exe) os.chmod(c2d_exe, st.st_mode | stat.S_IEXEC) self.myenv = os.environ.copy() self.myenv["PATH"] = os.pathsep.join(( self.bin_path.name, self.myenv["PATH"])) def tearDown(self): self.bin_path.cleanup() def test_c2d_input_format_npz_output_format_xyz(self): """c2d NaCl.npz NaCl.xyz""" print(" RUN test_c2d_input_format_npz_output_format_xyz") with tempfile.TemporaryDirectory() as tmpdir: subprocess.run( [ 'c2d', os.path.join(self.data_path,'NaCl.npz'), 'NaCl.xyz' ], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tmpdir, env=self.myenv) xyz = ase.io.read(os.path.join(tmpdir,'NaCl.xyz'), format='extxyz') self.assertEqual(len(xyz),len(self.ref_xyz)) self.assertTrue( ( xyz.symbols == self.ref_xyz.symbols ).all() ) self.assertTrue( ( xyz.get_initial_charges() == self.ref_xyz.get_initial_charges() ).all() ) self.assertTrue( ( xyz.cell == self.ref_xyz.cell ).all() ) def test_c2d_input_format_txt_output_format_xyz(self): """c2d NaCl.txt NaCl.xyz""" print(" RUN test_c2d_input_format_txt_output_format_xyz") with tempfile.TemporaryDirectory() as tmpdir: subprocess.run( [ 'c2d', os.path.join(self.data_path,'NaCl.txt'), 'NaCl.xyz' ], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tmpdir, env=self.myenv) xyz = ase.io.read(os.path.join(tmpdir,'NaCl.xyz'), format='extxyz') self.assertEqual(len(xyz), len(self.ref_xyz)) self.assertTrue( ( xyz.symbols == self.ref_xyz.symbols ).all() ) self.assertTrue( ( xyz.get_initial_charges() == self.ref_xyz.get_initial_charges() ).all() ) self.assertTrue( ( xyz.cell == self.ref_xyz.cell ).all() ) @unittest.skipUnless(LooseVersion(ase.__version__) > LooseVersion('3.19.0'), """ LAMMPS data file won't work for ASE version up until 3.18.1, LAMMPS data file input broken in ASE 3.19.0, skipped""") def test_c2d_input_format_npz_output_format_lammps(self): """c2d NaCl.npz NaCl.lammps""" print(" RUN test_c2d_input_format_npz_output_format_lammps") with tempfile.TemporaryDirectory() as tmpdir: subprocess.run( [ 'c2d', os.path.join(self.data_path,'NaCl.npz'), 'NaCl.lammps' ], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tmpdir, env=self.myenv) lammps = ase.io.read( os.path.join(tmpdir,'NaCl.lammps'),format='lammps-data') self.assertEqual(len(lammps), len(self.ref_lammps)) self.assertTrue( ( lammps.symbols == self.ref_lammps.symbols ).all() ) self.assertTrue( ( lammps.get_initial_charges() == self.ref_lammps.get_initial_charges() ).all() ) self.assertTrue( ( lammps.cell == self.ref_lammps.cell ).all() ) def test_pnp_output_format_npz(self): """pnp -c 0.1 0.1 -u 0.05 -l 1.0e-7 -bc cell NaCl.npz""" print(" RUN test_pnp_output_format_npz") with tempfile.TemporaryDirectory() as tmpdir: subprocess.run( ['pnp', '-c', '0.1', '0.1', '-z', '1', '-1', '-u', '0.05', '-l', '1.0e-7', '-bc', 'cell', 'out.npz'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tmpdir, env=self.myenv) test_npz = np.load(os.path.join(tmpdir,'out.npz')) # depending on which solver is used for the tests, absolute values might deviate more than the default tolerance self.assertArrayAlmostEqual(test_npz['x'], self.ref_npz['x'], tol=1e-7) self.assertArrayAlmostEqual(test_npz['u'], self.ref_npz['u'], tol=1e-5) self.assertArrayAlmostEqual(test_npz['c'], self.ref_npz['c'], tol=1e-3) def test_pnp_output_format_txt(self): """pnp -c 0.1 0.1 -u 0.05 -l 1.0e-7 -bc cell NaCl.txt""" print(" RUN test_pnp_output_format_txt") with tempfile.TemporaryDirectory() as tmpdir: subprocess.run( ['pnp', '-c', '0.1', '0.1', '-z', '1', '-1', '-u', '0.05', '-l', '1.0e-7', '-bc', 'cell', 'out.txt'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tmpdir, env=self.myenv) test_txt = np.loadtxt(os.path.join(tmpdir,'out.txt'), unpack=True) # depending on which solver is used for the tests, absolute values might deviate more than the default tolerance self.assertArrayAlmostEqual(test_txt[0,:], self.ref_txt[0,:], tol=1e-5) # x self.assertArrayAlmostEqual(test_txt[1,:],self.ref_txt[1,:], tol=1e-5) # u self.assertArrayAlmostEqual(test_txt[2:,:],self.ref_txt[2:,:], tol=1e-3) # c def test_pnp_c2d_pipeline_mode(self): """pnp -c 0.1 0.1 -u 0.05 -l 1.0e-7 -bc cell | c2d > NaCl.xyz""" print(" RUN test_pnp_c2d_pipeline_mode") with tempfile.TemporaryDirectory() as tmpdir: pnp = subprocess.Popen( ['pnp', '-c', '0.1', '0.1', '-z', '1', '-1', '-u', '0.05', '-l', '1.0e-7', '-bc', 'cell'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tmpdir, encoding='utf-8', env=self.myenv) c2d = subprocess.Popen([ 'c2d' ], stdin=pnp.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tmpdir, encoding='utf-8', env=self.myenv) pnp.stdout.close() # Allow pnp to receive a SIGPIPE if p2 exits. self.assertEqual(c2d.wait(),0) self.assertEqual(pnp.wait(),0) c2d_output = c2d.communicate()[0] with io.StringIO(c2d_output) as xyz_instream: xyz = ase.io.read(xyz_instream, format='extxyz') self.assertEqual(len(xyz),len(self.ref_xyz)) self.assertTrue( ( xyz.symbols == self.ref_xyz.symbols ).all() ) self.assertTrue( ( xyz.get_initial_charges() == self.ref_xyz.get_initial_charges() ).all() ) self.assertTrue( ( xyz.cell == self.ref_xyz.cell ).all() )
9,534
47.156566
124
py
matscipy
matscipy-master/tests/test_polydisperse_calculator.py
# # Copyright 2020-2021 Jan Griesser (U. Freiburg) # 2020-2021 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import random import pytest import sys import numpy as np import ase.io as io import ase.constraints from ase import Atoms from ase.lattice.cubic import FaceCenteredCubic from ase.optimize import FIRE import matscipy.calculators.polydisperse as calculator from matscipy.elasticity import ( full_3x3x3x3_to_Voigt_6x6, measure_triclinic_elastic_constants, nonaffine_elastic_contribution ) from matscipy.calculators.polydisperse import InversePowerLawPotential, Polydisperse from matscipy.numerical import ( numerical_forces, numerical_stress, numerical_hessian, numerical_nonaffine_forces, ) def test_forces_dimer(): """ Check forces for a dimer """ d = 1.2 L = 10 atomic_configuration = Atoms("HH", positions=[(L/2, L/2, L/2), (L/2 + d, L/2, L/2)], cell=[L, L, L], pbc=[1, 1, 1] ) atomic_configuration.set_array("size", np.array([1.3, 2.22]), dtype=float) atomic_configuration.set_masses(masses = np.repeat(1.0, len(atomic_configuration))) calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atomic_configuration.calc = calc f = atomic_configuration.get_forces() fn = numerical_forces(atomic_configuration, d=1e-5) np.testing.assert_allclose(f, fn, atol=1e-4, rtol=1e-4) def test_forces_crystal(): """ Check forces for a crystalline configuration """ atoms = FaceCenteredCubic('H', size=[2, 2, 2], latticeconstant=2.37126) calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atoms.set_masses(masses = np.repeat(1.0, len(atoms))) atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float) atoms.calc = calc f = atoms.get_forces() fn = numerical_forces(atoms, d=1e-5) np.testing.assert_allclose(f, fn, atol=1e-4, rtol=1e-4) @pytest.mark.parametrize('a0', [2.0, 2.5, 3.0]) def test_crystal_stress(a0): """ Test the computation of stresses for a crystal """ calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atoms = FaceCenteredCubic('H', size=[2, 2, 2], latticeconstant=a0) atoms.set_masses(masses=np.repeat(1.0, len(atoms))) atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float) atoms.calc = calc s = atoms.get_stress() sn = numerical_stress(atoms, d=1e-5) np.testing.assert_allclose(s, sn, atol=1e-4, rtol=1e-4) def test_glass_stress(): """ Test the computation of stresses for a glass """ calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atoms = io.read('glass_min.xyz') atoms.set_masses(masses=np.repeat(1.0, len(atoms))) atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float) atoms.set_atomic_numbers(np.repeat(1.0, len(atoms))) atoms.calc = calc s = atoms.get_stress() sn = numerical_stress(atoms, d=1e-5) np.testing.assert_allclose(s, sn, atol=1e-4, rtol=1e-4) def test_symmetry_sparse(): """ Test the symmetry of the dense Hessian matrix """ atoms = FaceCenteredCubic('H', size=[2,2,2], latticeconstant=2.37126) calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atoms.set_masses(masses=np.repeat(1.0, len(atoms))) atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float) atoms.calc = calc FIRE(atoms, logfile=None).run(fmax=1e-5) H = calc.get_property('hessian', atoms).todense() np.testing.assert_allclose(np.sum(np.abs(H-H.T)), 0, atol=1e-6, rtol=1e-6) def test_hessian_random_structure(): """ Test the computation of the Hessian matrix """ atoms = FaceCenteredCubic('H', size=[2,2,2], latticeconstant=2.37126) calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atoms.set_masses(masses=np.repeat(1.0, len(atoms))) atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float) atoms.calc = calc FIRE(atoms, logfile=None).run(fmax=1e-5) H_analytical = atoms.calc.get_property('hessian', atoms).todense() H_numerical = numerical_hessian(atoms, d=1e-5, indices=None).todense() np.testing.assert_allclose(H_analytical, H_numerical, atol=1e-4, rtol=1e-6) def test_hessian_divide_by_masses(): """ Test the computation of the Hessian matrix """ atoms = FaceCenteredCubic('H', size=[2,2,2], latticeconstant=2.37126) atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float) masses_n = np.random.randint(1, 10, size=len(atoms)) atoms.set_masses(masses=masses_n) calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atoms.calc = calc FIRE(atoms, logfile=None).run(fmax=1e-5) D_analytical = calc.get_property('dynamical_matrix', atoms).todense() H_analytical = calc.get_property('hessian', atoms).todense() masses_nc = masses_n.repeat(3) H_analytical /= np.sqrt(masses_nc.reshape(-1,1)*masses_nc.reshape(1,-1)) np.testing.assert_allclose(H_analytical, D_analytical, atol=1e-6, rtol=1e-6) @pytest.mark.parametrize('a0', [2.5, 3.0]) def test_crystal_non_affine_forces(a0): """ Test the computation of the non-affine forces for a crystal """ calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atoms = FaceCenteredCubic('H', size=[2,2,2], latticeconstant=a0) atoms.set_masses(masses=np.repeat(1.0, len(atoms))) atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float) atoms.calc = calc FIRE(atoms, logfile=None).run(fmax=1e-6) naForces_num = numerical_nonaffine_forces(atoms, d=1e-6) naForces_ana = calc.get_property('nonaffine_forces', atoms) np.testing.assert_allclose(naForces_num, naForces_ana, atol=1e-2) def test_glass_non_affine_forces(): """ Test the computation of the non-affine forces for a glass """ calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atoms = io.read("glass_min.xyz") atoms.set_masses(masses=np.repeat(1.0, len(atoms))) atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float) atoms.set_atomic_numbers(np.repeat(1.0, len(atoms))) atoms.calc = calc FIRE(atoms, logfile=None).run(fmax=1e-6) naForces_num = numerical_nonaffine_forces(atoms, d=1e-6) naForces_ana = calc.get_property('nonaffine_forces', atoms) np.testing.assert_allclose(naForces_num, naForces_ana, atol=1)
8,524
40.995074
87
py
matscipy
matscipy-master/tests/test_ewald.py
# # Copyright 2018-2021 Jan Griesser (U. Freiburg) # 2014, 2020-2021 Lars Pastewka (U. Freiburg) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import pytest import numpy as np from ase.optimize import FIRE from ase.units import GPa from ase.lattice.hexagonal import HexagonalFactory from ase.lattice.cubic import SimpleCubicFactory from ase.calculators.mixing import SumCalculator from matscipy.calculators.ewald import Ewald from matscipy.calculators.pair_potential.calculator import ( PairPotential, BeestKramerSanten, ) from matscipy.numerical import ( numerical_hessian, numerical_nonaffine_forces, numerical_forces, numerical_stress, ) from matscipy.elasticity import ( fit_elastic_constants, full_3x3x3x3_to_Voigt_6x6, nonaffine_elastic_contribution, ) ### class alpha_quartz(HexagonalFactory): """ Factory to create an alpha quartz crystal structure """ xtal_name = "alpha_quartz" bravais_basis = [ [0, 0.4763, 0.6667], [0.4763, 0, 0.3333], [0.5237, 0.5237, 0], [0.1588, 0.7439, 0.4612], [0.2561, 0.4149, 0.7945], [0.4149, 0.2561, 0.2055], [0.5851, 0.8412, 0.1279], [0.7439, 0.1588, 0.5388], [0.8412, 0.5851, 0.8721], ] element_basis = (0, 0, 0, 1, 1, 1, 1, 1, 1) class beta_cristobalite(SimpleCubicFactory): """ Factory to create a beta cristobalite crystal structure """ xtal_name = "beta_cristobalite" bravais_basis = [ [0.98184000, 0.51816000, 0.48184000], [0.51816000, 0.48184000, 0.98184000], [0.48184000, 0.98184000, 0.51816000], [0.01816000, 0.01816000, 0.01816000], [0.72415800, 0.77584200, 0.22415800], [0.77584200, 0.22415800, 0.72415800], [0.22415800, 0.72415800, 0.77584200], [0.27584200, 0.27584200, 0.27584200], [0.86042900, 0.34389100, 0.55435200], [0.36042900, 0.15610900, 0.44564800], [0.13957100, 0.84389100, 0.94564800], [0.15610900, 0.44564800, 0.36042900], [0.94564800, 0.13957100, 0.84389100], [0.44564800, 0.36042900, 0.15610900], [0.34389100, 0.55435200, 0.86042900], [0.55435200, 0.86042900, 0.34389100], [0.14694300, 0.14694300, 0.14694300], [0.35305700, 0.85305700, 0.64694300], [0.64694300, 0.35305700, 0.85305700], [0.85305700, 0.64694300, 0.35305700], [0.63957100, 0.65610900, 0.05435200], [0.05435200, 0.63957100, 0.65610900], [0.65610900, 0.05435200, 0.63957100], [0.84389100, 0.94564800, 0.13957100], ] element_basis = tuple([0] * 8 + [1] * 16) calc_alpha_quartz = { (14, 14): BeestKramerSanten(0, 1, 0, 2.9), (14, 8): BeestKramerSanten(18003.7572, 4.87318, 133.5381, 2.9), (8, 8): BeestKramerSanten(1388.7730, 2.76000, 175.0000, 2.9), } ewald_alpha_params = dict( accuracy=1e-6, cutoff=2.9, kspace={ "alpha": 1.28, "nbk_c": np.array([8, 11, 9]), "cutoff": 10.43, }, ) calc_beta_cristobalite = calc_alpha_quartz.copy() for k in calc_beta_cristobalite: calc_beta_cristobalite[k].cutoff = 3.8 ewald_beta_params = dict( accuracy=1e-6, cutoff=3.8, kspace={ "alpha": 0.96, "nbk_c": np.array([9, 9, 9]), "cutoff": 7, }, ) @pytest.fixture(scope="module", params=[4.7, 4.9, 5.1]) def alpha_quartz_ewald(request): structure = alpha_quartz() a0 = request.param atoms = structure( ["Si", "O"], size=[1, 1, 1], latticeconstant={"a": a0, "b": a0, "c": 5.4}, ) charges = np.zeros(len(atoms)) charges[atoms.symbols == "Si"] = +2.4 charges[atoms.symbols == "O"] = -1.2 atoms.set_array("charge", charges, dtype=float) b = Ewald() b.set(**ewald_alpha_params) atoms.calc = b return atoms @pytest.fixture(scope="module") def alpha_quartz_bks(alpha_quartz_ewald): atoms = alpha_quartz_ewald atoms.calc = SumCalculator([atoms.calc, PairPotential(calc_alpha_quartz)]) FIRE(atoms, logfile=None).run(fmax=1e-3) return atoms @pytest.fixture(scope="module") def beta_cristobalite_ewald(request): a0 = request.param structure = beta_cristobalite() atoms = structure(["Si", "O"], size=[1, 1, 1], latticeconstant=a0) charges = np.zeros(len(atoms)) charges[atoms.symbols == "Si"] = +2.4 charges[atoms.symbols == "O"] = -1.2 atoms.set_array("charge", charges, dtype=float) b = Ewald() b.set(**ewald_beta_params) atoms.calc = b return atoms @pytest.fixture(scope="module") def beta_cristobalite_bks(request): a0 = request.param structure = beta_cristobalite() atoms = structure(["Si", "O"], size=[1, 1, 1], latticeconstant=a0) charges = np.zeros(len(atoms)) charges[atoms.symbols == "Si"] = +2.4 charges[atoms.symbols == "O"] = -1.2 atoms.set_array("charge", charges, dtype=float) b = Ewald() b.set(**ewald_beta_params) atoms.calc = b atoms.calc = SumCalculator( [atoms.calc, PairPotential(calc_beta_cristobalite)] ) FIRE(atoms, logfile=None).run(fmax=1e-3) return atoms # Test for alpha quartz def test_stress_alpha_quartz(alpha_quartz_ewald): """ Test the computation of stress """ atoms = alpha_quartz_ewald s = atoms.get_stress() sn = numerical_stress(atoms, d=0.001) print("Stress ana: \n", s) print("Stress num: \n", sn) np.testing.assert_allclose(s, sn, atol=1e-3) def test_forces_alpha_quartz(alpha_quartz_ewald): """ Test the computation of forces """ atoms = alpha_quartz_ewald f = atoms.get_forces() fn = numerical_forces(atoms, d=0.0001) print("f_ana: \n", f[:5, :]) print("f_num: \n", fn[:5, :]) np.testing.assert_allclose(f, fn, atol=1e-3) def test_hessian_alpha_quartz(alpha_quartz_bks): """ Test the computation of the Hessian matrix """ atoms = alpha_quartz_bks H_num = numerical_hessian(atoms, d=1e-5, indices=None) H_ana = atoms.calc.get_property("hessian", atoms) print("H_num: \n", H_num.todense()[:6, :6]) print("H_ana: \n", H_ana[:6, :6]) np.testing.assert_allclose(H_num.todense(), H_ana, atol=1e-3) def test_non_affine_forces_alpha_quartz(alpha_quartz_bks): """ Test the computation of non-affine forces """ atoms = alpha_quartz_bks naForces_ana = atoms.calc.get_property("nonaffine_forces") naForces_num = numerical_nonaffine_forces(atoms, d=1e-5) print("Num: \n", naForces_num[:1]) print("Ana: \n", naForces_ana[:1]) np.testing.assert_allclose(naForces_num, naForces_ana, atol=1e-2) def test_birch_coefficients_alpha_quartz(alpha_quartz_bks): """ Test the computation of the affine elastic constants + stresses """ atoms = alpha_quartz_bks C_ana = full_3x3x3x3_to_Voigt_6x6( atoms.calc.get_property("birch_coefficients"), check_symmetry=False ) C_num, Cerr = fit_elastic_constants( atoms, symmetry="triclinic", N_steps=11, delta=1e-5, optimizer=None, verbose=False, ) print("Stress: \n", atoms.get_stress() / GPa) print("C_num: \n", C_num / GPa) print("C_ana: \n", C_ana / GPa) np.testing.assert_allclose(C_num, C_ana, atol=1e-1) def test_full_elastic_alpha_quartz(alpha_quartz_bks): """ Test the computation of the affine elastic constants + stresses + non-affine elastic constants """ atoms = alpha_quartz_bks C_num, Cerr = fit_elastic_constants( atoms, symmetry="triclinic", N_steps=11, delta=1e-4, optimizer=FIRE, fmax=1e-4, logfile=None, verbose=False, ) C_ana = full_3x3x3x3_to_Voigt_6x6( atoms.calc.get_property("birch_coefficients"), check_symmetry=False ) C_na = full_3x3x3x3_to_Voigt_6x6( nonaffine_elastic_contribution(atoms) ) print("stress: \n", atoms.get_stress()) print("C_num: \n", C_num) print("C_ana: \n", C_ana + C_na) np.testing.assert_allclose(C_num, C_ana + C_na, atol=1e-1) ### # Beta crisotbalite @pytest.mark.parametrize( "beta_cristobalite_ewald", [6, 7, 8, 9], indirect=True ) def test_stress_beta_cristobalite(beta_cristobalite_ewald): """ Test the computation of stress """ atoms = beta_cristobalite_ewald s = atoms.get_stress() sn = numerical_stress(atoms, d=0.0001) print("Stress ana: \n", s) print("Stress num: \n", sn) np.testing.assert_allclose(s, sn, atol=1e-3) @pytest.mark.parametrize( "beta_cristobalite_ewald", [6, 7, 8, 9], indirect=True ) def test_forces_beta_cristobalite(beta_cristobalite_ewald): """ Test the computation of forces """ atoms = beta_cristobalite_ewald f = atoms.get_forces() fn = numerical_forces(atoms, d=1e-5) print("forces ana: \n", f[:5, :]) print("forces num: \n", fn[:5, :]) np.testing.assert_allclose(f, fn, atol=1e-3) @pytest.mark.parametrize("beta_cristobalite_bks", [6, 7, 8, 9], indirect=True) def test_hessian_beta_cristobalite(beta_cristobalite_bks): """ Test the computation of the Hessian matrix """ atoms = beta_cristobalite_bks H_num = numerical_hessian(atoms, d=1e-5, indices=None) H_ana = atoms.calc.get_property("hessian") np.testing.assert_allclose(H_num.todense(), H_ana, atol=1e-3) @pytest.mark.parametrize("beta_cristobalite_bks", [6], indirect=True) def test_non_affine_forces_beta_cristobalite(beta_cristobalite_bks): """ Test the computation of non-affine forces """ atoms = beta_cristobalite_bks naForces_ana = atoms.calc.get_property("nonaffine_forces") naForces_num = numerical_nonaffine_forces(atoms, d=1e-5) print("Num: \n", naForces_num[:1]) print("Ana: \n", naForces_ana[:1]) np.testing.assert_allclose(naForces_num, naForces_ana, atol=1e-2) @pytest.mark.parametrize("beta_cristobalite_bks", [6], indirect=True) def test_birch_coefficients_beta_cristobalite(beta_cristobalite_bks): """ Test the computation of the affine elastic constants + stresses """ atoms = beta_cristobalite_bks C_num, Cerr = fit_elastic_constants( atoms, symmetry="triclinic", N_steps=11, delta=1e-5, optimizer=None, verbose=False, ) C_ana = full_3x3x3x3_to_Voigt_6x6( atoms.calc.get_property("birch_coefficients"), check_symmetry=False ) print("C_num: \n", C_num) print("C_ana: \n", C_ana) np.testing.assert_allclose(C_num, C_ana, atol=1e-1) @pytest.mark.parametrize("beta_cristobalite_bks", [6], indirect=True) def test_non_affine_elastic_beta_cristobalite(beta_cristobalite_bks): """ Test the computation of the affine elastic constants + stresses + non-affine elastic constants """ atoms = beta_cristobalite_bks C_num, Cerr = fit_elastic_constants( atoms, symmetry="triclinic", N_steps=11, delta=1e-3, optimizer=FIRE, fmax=1e-3, logfile=None, verbose=False, ) C_ana = full_3x3x3x3_to_Voigt_6x6( atoms.calc.get_property("birch_coefficients"), check_symmetry=False ) C_na = full_3x3x3x3_to_Voigt_6x6( nonaffine_elastic_contribution(atoms) ) print("stress: \n", atoms.get_stress()) print("C_num: \n", C_num) print("C_ana: \n", C_ana + C_na) np.testing.assert_allclose(C_num, C_ana + C_na, atol=1e-1)
13,201
27.888403
78
py
matscipy
matscipy-master/tests/test_cubic_crystal_crack.py
# # Copyright 2014-2015, 2017, 2020-2021 Lars Pastewka (U. Freiburg) # 2020 Johannes Hoermann (U. Freiburg) # 2014, 2017 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import math import unittest import numpy as np try: from scipy.integrate import quadrature except: quadrature = None import ase.io from ase.constraints import FixAtoms from ase.optimize import FIRE from ase.lattice.cubic import FaceCenteredCubic, SimpleCubic import matscipytest import matscipy.fracture_mechanics.clusters as clusters from matscipy.neighbours import neighbour_list from matscipy.elasticity import measure_triclinic_elastic_constants from matscipy.elasticity import Voigt_6x6_to_cubic from matscipy.fracture_mechanics.crack import CubicCrystalCrack from matscipy.fracture_mechanics.crack import \ isotropic_modeI_crack_tip_displacement_field from matscipy.fracture_mechanics.idealbrittlesolid import IdealBrittleSolid ### class TestCubicCrystalCrack(matscipytest.MatSciPyTestCase): delta = 1e-6 def setUp(self): E = 100 nu = 0.3 K = E/(3.*(1-2*nu)) C44 = E/(2.*(1+nu)) C11 = K+4.*C44/3. C12 = K-2.*C44/3. # C11, C12, C44, surface energy, k1 self.materials = [(1.0, 0.5, 0.3, 1.0, 1.0), (1.0, 0.7, 0.3, 1.3, 1.0), (C11, C12, C44, 1.77, 1.0)] #self.materials = [(C11, C12, C44, 1.0, 1.0)] def test_isotropic_near_field_solution(self): """ Check if we recover the near field solution for isotropic cracks. """ E = 100 nu = 0.3 K = E/(3.*(1-2*nu)) C44 = E/(2.*(1+nu)) C11 = K+4.*C44/3. C12 = K-2.*C44/3. kappa = 3-4*nu #kappa = 4./(1+nu)-1 crack = CubicCrystalCrack([1,0,0], [0,1,0], C11, C12, C44) #r = np.random.random(10)*10 #theta = np.random.random(10)*2*math.pi theta = np.linspace(0.0, math.pi, 101) r = np.linspace(0.5, 10.0, 101) k = crack.crack.k1g(1.0) u, v = crack.crack.displacements(r, theta, k) ref_u, ref_v = isotropic_modeI_crack_tip_displacement_field(k, C44, nu, r, theta) self.assertArrayAlmostEqual(u, ref_u) self.assertArrayAlmostEqual(v, ref_v) def test_anisotropic_near_field_solution(self): """ Run an atomistic calculation of a harmonic solid and compare to continuum solution. """ for nx in [ 8, 16, 32, 64 ]: for calc, a, C11, C12, C44, surface_energy, bulk_coordination in [ #( atomistica.DoubleHarmonic(k1=1.0, r1=1.0, k2=1.0, # r2=math.sqrt(2), cutoff=1.6), # clusters.sc('He', 1.0, [nx,nx,1], [1,0,0], [0,1,0]), # 3, 1, 1, 0.05, 6 ), ( #atomistica.Harmonic(k=1.0, r0=1.0, cutoff=1.3, shift=True), IdealBrittleSolid(k=1.0, a=1.0, rc=1.3), clusters.fcc('He', math.sqrt(2.0), [nx,nx,1], [1,0,0], [0,1,0]), math.sqrt(2), 1.0/math.sqrt(2), 1.0/math.sqrt(2), 0.05, 12) ]: clusters.set_groups(a, (nx, nx, 1), 0.5, 0.5) crack = CubicCrystalCrack([1,0,0], [0,1,0], C11, C12, C44) a.center(vacuum=20.0, axis=0) a.center(vacuum=20.0, axis=1) a.set_calculator(calc) sx, sy, sz = a.cell.diagonal() tip_x = sx/2 tip_y = sy/2 k1g = crack.k1g(surface_energy) r0 = a.positions.copy() u, v = crack.displacements(a.positions[:,0], a.positions[:,1], tip_x, tip_y, k1g) a.positions[:,0] += u a.positions[:,1] += v g = a.get_array('groups') a.set_constraint(FixAtoms(mask=g==0)) #ase.io.write('initial_{}.xyz'.format(nx), a, format='extxyz', write_results=False) x1, y1, z1 = a.positions.copy().T FIRE(a, logfile=None).run(fmax=1e-3) x2, y2, z2 = a.positions.T # Get coordination numbers and find properly coordinated atoms i = neighbour_list("i", a, 1.1) coord = np.bincount(i, minlength=len(a)) mask=coord == bulk_coordination residual = np.sqrt(((x2-x1)/u)**2 + ((y2-y1)/v)**2) #a.set_array('residual', residual) #ase.io.write('final_{}.xyz'.format(nx), a, format='extxyz') #print(np.max(residual[mask])) self.assertTrue(np.max(residual[mask]) < 0.2) def test_consistency_of_deformation_gradient_and_stress(self): for C11, C12, C44, surface_energy, k1 in self.materials: crack = CubicCrystalCrack([1,0,0], [0,1,0], C11, C12, C44) k = crack.k1g(surface_energy)*k1 for i in range(10): x = np.random.uniform(-10, 10) y = np.random.uniform(-10, 10) F = crack.deformation_gradient(x, y, 0, 0, k) eps = (F+F.T)/2-np.eye(2) sig_x, sig_y, sig_xy = crack.stresses(x, y, 0, 0, k) eps_xx = crack.crack.a11*sig_x + \ crack.crack.a12*sig_y + \ crack.crack.a16*sig_xy eps_yy = crack.crack.a12*sig_x + \ crack.crack.a22*sig_y + \ crack.crack.a26*sig_xy # Factor 1/2 because elastic constants and matrix product are # expressed in Voigt notation. eps_xy = (crack.crack.a16*sig_x + \ crack.crack.a26*sig_y + \ crack.crack.a66*sig_xy)/2 self.assertAlmostEqual(eps[0, 0], eps_xx) self.assertAlmostEqual(eps[1, 1], eps_yy) self.assertAlmostEqual(eps[0, 1], eps_xy) def test_consistency_of_deformation_gradient_and_displacement(self): eps = 1e-3 for C11, C12, C44, surface_energy, k1 in self.materials: crack = CubicCrystalCrack([1,0,0], [0,1,0], C11, C12, C44) k = crack.k1g(surface_energy)*k1 for i in range(10): x = i+1 y = i+1 F = crack.deformation_gradient(x, y, 0, 0, k) # Finite difference approximation of deformation gradient u, v = crack.displacements(x, y, 0, 0, k) ux0, vx0 = crack.displacements(x-eps, y, 0, 0, k) uy0, vy0 = crack.displacements(x, y-eps, 0, 0, k) ux1, vx1 = crack.displacements(x+eps, y, 0, 0, k) uy1, vy1 = crack.displacements(x, y+eps, 0, 0, k) du_dx = (ux1-ux0)/(2*eps) du_dy = (uy1-uy0)/(2*eps) dv_dx = (vx1-vx0)/(2*eps) dv_dy = (vy1-vy0)/(2*eps) du_dx += np.ones_like(du_dx) dv_dy += np.ones_like(dv_dy) F_num = np.transpose([[du_dx, du_dy], [dv_dx, dv_dy]]) self.assertArrayAlmostEqual(F, F_num, tol=1e-4) def test_elastostatics(self): eps = 1e-3 for C11, C12, C44, surface_energy, k1 in self.materials: crack = CubicCrystalCrack([1,0,0], [0,1,0], C11, C12, C44) k = crack.k1g(surface_energy)*k1 for i in range(10): x = i+1 y = i+1 # Finite difference approximation of the stress divergence sxx0x, syy0x, sxy0x = crack.stresses(x-eps, y, 0, 0, k) sxx0y, syy0y, sxy0y = crack.stresses(x, y-eps, 0, 0, k) sxx1x, syy1x, sxy1x = crack.stresses(x+eps, y, 0, 0, k) sxx1y, syy1y, sxy1y = crack.stresses(x, y+eps, 0, 0, k) divsx = (sxx1x-sxx0x)/(2*eps) + (sxy1y-sxy0y)/(2*eps) divsy = (sxy1x-sxy0x)/(2*eps) + (syy1y-syy0y)/(2*eps) # Check that divergence of stress is zero (elastostatic # equilibrium) self.assertAlmostEqual(divsx, 0.0, places=3) self.assertAlmostEqual(divsy, 0.0, places=3) def test_J_integral(self): if quadrature is None: print('No scipy.integrate.quadrature. Skipping J-integral test.') return for C11, C12, C44, surface_energy, k1 in self.materials: crack = CubicCrystalCrack([1,0,0], [0,1,0], C11, C12, C44) k = crack.k1g(surface_energy)*k1 def polar_path(theta, r=1, x0=0, y0=0): nx = np.cos(theta) ny = np.sin(theta) n = np.transpose([nx, ny]) return r*n-np.array([x0, y0]), n, r def elliptic_path(theta, r=1, x0=0, y0=0): rx, ry = r x = rx*np.cos(theta) y = ry*np.sin(theta) nx = ry*np.cos(theta) ny = rx*np.sin(theta) ln = np.sqrt(nx**2+ny**2) nx /= ln ny /= ln ds = np.sqrt((rx*np.sin(theta))**2 + (ry*np.cos(theta))**2) return np.transpose([x-x0, y-y0]), np.transpose([nx, ny]), ds def rectangular_path(t, r): x = -r*np.ones_like(t) y = r*(t-8) nx = -np.ones_like(t) ny = np.zeros_like(t) x = np.where(t < 7, r*(6-t), x) y = np.where(t < 7, -r*np.ones_like(t), y) nx = np.where(t < 7, np.zeros_like(t), nx) ny = np.where(t < 7, -np.ones_like(t), ny) x = np.where(t < 5, r*np.ones_like(t), x) y = np.where(t < 5, r*(4-t), y) nx = np.where(t < 5, np.ones_like(t), nx) ny = np.where(t < 5, np.zeros_like(t), ny) x = np.where(t < 3, r*(t-2), x) y = np.where(t < 3, r*np.ones_like(t), y) nx = np.where(t < 3, np.zeros_like(t), nx) ny = np.where(t < 3, np.ones_like(t), ny) x = np.where(t < 1, -r*np.ones_like(t), x) y = np.where(t < 1, r*t, y) nx = np.where(t < 1, -np.ones_like(t), nx) ny = np.where(t < 1, np.zeros_like(t), ny) return np.transpose([x, y]), np.transpose([nx, ny]), r def J(t, path_func=polar_path): # Position, normal to path, length pos, n, ds = path_func(t) x, y = pos.T nx, ny = n.T # Stress tensor sxx, syy, sxy = crack.stresses(x, y, 0, 0, k) s = np.array([[sxx, sxy], [sxy, syy]]).T # Deformation gradient and strain tensor F = crack.deformation_gradient(x, y, 0, 0, k) eps = (F+F.swapaxes(1, 2))/2 - np.identity(2).reshape(1, 2, 2) # Strain energy density W = (s*eps).sum(axis=2).sum(axis=1)/2 # Note dy == nx*ds retval = (W*nx - np.einsum('...j,...jk,...k->...', n, s, F[..., 0, :]))*ds return retval eps = 1e-6 for r in [1, 10, 100]: # Polar path J_val, J_err = quadrature(J, -np.pi+eps, np.pi-eps, args=(lambda t: polar_path(t, r)), ) self.assertAlmostEqual(J_val, 2*surface_energy, places=2) # Elliptic path J_val, J_err = quadrature(J, -np.pi+eps, np.pi-eps, args=(lambda t: elliptic_path(t, (3*r, r)), ), maxiter=200) self.assertAlmostEqual(J_val, 2*surface_energy, places=2) # Elliptic path, shifted in x and y directions off-center J_val, J_err = quadrature(J, -np.pi+eps, np.pi-eps, args=(lambda t: elliptic_path(t, (r, 1.5*r), 0, 0.5), ), maxiter=200) self.assertAlmostEqual(J_val, 2*surface_energy, places=2) #J_val, J_err = quadrature(J, eps, 8-eps, args=(r, rectangular_path)) #print('rectangular: J =', J_val, J_err) #self.assertAlmostEqual(J_val, surface_energy, places=2) ### if __name__ == '__main__': unittest.main()
14,380
41.049708
99
py
matscipy
matscipy-master/tests/run_tests.py
# # Copyright 2014-2017, 2021 Lars Pastewka (U. Freiburg) # 2020-2021 Jan Griesser (U. Freiburg) # 2020 Thomas Reichenbach (Fraunhofer IWM) # 2018, 2020 Petr Grigorev (Warwick U.) # 2019-2020 Johannes Hoermann (U. Freiburg) # 2018 Jacek Golebiowski (Imperial College London) # 2016 Punit Patel (Warwick U.) # 2016 Richard Jana (KIT & U. Freiburg) # 2014 James Kermode (Warwick U.) # # matscipy - Materials science with Python at the atomic-scale # https://github.com/libAtoms/matscipy # # 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 2 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/>. # # ====================================================================== # matscipy - Python materials science tools # https://github.com/libAtoms/matscipy # # Copyright (2014) James Kermode, King's College London # Lars Pastewka, Karlsruhe Institute of Technology # # 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 2 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/>. # ====================================================================== import sys import unittest from analysis import * from angle_distribution import * from cubic_crystal_crack import * from eam_io import * from elastic_moduli import * from fit_elastic_constants import * from full_to_Voigt import * from greens_function import * from Hertz import * from hydrogenate import * from idealbrittlesolid import * from invariants import * from neighbours import * from ring_statistics import * from spatial_correlation_function import * from test_io import * from crack_tests import * from mcfm_test import * from hessian_finite_differences import * from eam_calculator_forces_and_hessian import * from pair_potential_calculator import * from polydisperse_calculator import * from bopsw import * if sys.version_info.major > 2: from test_c2d import * from test_poisson_nernst_planck_solver import * else: print('Electrochemistry module requires python 3, related tests ' '(test_c2d, test_poisson_nernst_planck_solver) skipped.') try: from scipy.interpolate import InterpolatedUnivariateSpline except: print('No scipy.interpolate.InterpolatedUnivariateSpline, skipping ' 'EAM test.') else: print('EAM tests (eam_calculate, rotation_of_elastic_constants) are ' 'broken with added scipy 1.2.3 and otherwise current matscipy 0.3.0 ' 'Travis CI configuration (ase 3.13.0, numpy 1.12.1), hence skipped.') # from eam_calculator import * # from rotation_of_elastic_constants import * # tests requiring these imports are skipped individually with unittest.skipIf() # try: # from scipy.optimize import minimize # import matplotlib.pyplot # import atomman # except: # print('One of these missing: scipy.optimize.minimize, matplotlib.pyplot, ' # ' atomman. Skipping dislocation test.') # else: from test_dislocation import * from test_pressurecoupling import * from test_opls import * from test_opls_io import * ### unittest.main()
4,146
35.377193
80
py
matscipy
matscipy-master/tests/test_hessian_precon.py
import unittest import numpy as np import matscipytest import scipy.sparse.linalg as sla from matscipy.calculators.eam import EAM from matscipy.precon import HessianPrecon from numpy.linalg import norm from numpy.testing import assert_allclose from ase.build import bulk from ase.optimize.precon import PreconLBFGS from ase.optimize import ODE12r, LBFGS from ase.neb import NEB, NEBOptimizer from ase.geometry.geometry import get_distances class TestHessianPrecon(matscipytest.MatSciPyTestCase): def setUp(self): self.atoms = bulk("Ni", cubic=True) * 3 del self.atoms[0] np.random.seed(0) self.atoms.rattle(1e-2) self.eam = EAM('Mishin-Ni-Al-2009.eam.alloy') self.tol = 1e-6 def test_newton_opt(self): atoms, eam = self.atoms, self.eam f = eam.get_forces(atoms) norm_f = norm(f, np.inf) while norm_f > self.tol: H = eam.get_hessian(atoms).tocsc() D, P = sla.eigs(H, which='SM') print(D[D > 1e-6]) print(f'|F| = {norm_f:12.6f}') step = sla.spsolve(H, f.reshape(-1)).reshape(-1, 3) atoms.positions += step f = eam.get_forces(atoms) norm_f = norm(f, np.inf) def test_precon_opt(self): atoms, eam = self.atoms, self.eam noprecon_atoms = atoms.copy() atoms.calc = eam noprecon_atoms.calc = eam opt = PreconLBFGS(atoms, precon=HessianPrecon()) opt.run(fmax=self.tol) opt = LBFGS(noprecon_atoms) opt.run(fmax=self.tol) assert_allclose( atoms.positions, noprecon_atoms.positions, atol=self.tol) def test_precon_neb(self): N_cell = 4 N_intermediate = 5 initial = bulk('Ni', cubic=True) initial *= N_cell # place vacancy near centre of cell D, D_len = get_distances( np.diag(initial.cell) / 2, initial.positions, initial.cell, initial.pbc) vac_index = D_len.argmin() vac_pos = initial.positions[vac_index] del initial[vac_index] # identify two opposing nearest neighbours of the vacancy D, D_len = get_distances(vac_pos, initial.positions, initial.cell, initial.pbc) D = D[0, :] D_len = D_len[0, :] nn_mask = np.abs(D_len - D_len.min()) < 1e-8 i1 = nn_mask.nonzero()[0][0] i2 = ((D + D[i1])**2).sum(axis=1).argmin() print(f'vac_index={vac_index} i1={i1} i2={i2} ' f'distance={initial.get_distance(i1, i2, mic=True)}') final = initial.copy() final.positions[i1] = vac_pos initial.calc = self.eam final.calc = self.eam precon = HessianPrecon(c_stab=0.1) qn = ODE12r(initial, precon=precon) qn.run(fmax=1e-3) qn = ODE12r(final, precon=precon) qn.run(fmax=1e-3) images = [initial] for image in range(N_intermediate): image = initial.copy() image.calc = self.eam images.append(image) images.append(final) dummy_neb = NEB(images) dummy_neb.interpolate() neb = NEB( dummy_neb.images, allow_shared_calculator=True, precon=precon, method='spline') # neb.interpolate() opt = NEBOptimizer(neb) opt.run(fmax=0.1) # large tolerance for test speed if __name__ == '__main__': unittest.main()
3,508
28.241667
74
py