├── softpotato ├── grid.py ├── __pycache__ │ ├── __init__.cpython-38.pyc │ └── waveform.cpython-38.pyc ├── mainSP.py ├── waveform.py └── simulation.py ├── .gitignore ├── __pycache__ ├── plots.cpython-38.pyc └── waveforms.cpython-38.pyc ├── cottrell ├── __main__.py ├── mesh1d.py └── solver.py ├── plots.py ├── RK4_sp.py ├── README.md ├── BI-ads.py ├── BI_banded-E.py ├── FD-ECIrrev_ORY.py ├── BI-ads_RandCir.py ├── RK4-EC.py ├── FD-E.py ├── FD-E_OR.py ├── RK4-EC_R.py ├── ODEsol-E.py ├── RK4-E.py ├── BI-E_RandCirc.py ├── RK4-E_OR.py ├── waveforms.py ├── BI_banded-E_RandCirc.py ├── RK4_EC_OOP.py └── LICENSE /softpotato/grid.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | penv 2 | __pycache__* 3 | -------------------------------------------------------------------------------- /__pycache__/plots.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oliverrdz/EchemSimulations/HEAD/__pycache__/plots.cpython-38.pyc -------------------------------------------------------------------------------- /__pycache__/waveforms.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oliverrdz/EchemSimulations/HEAD/__pycache__/waveforms.cpython-38.pyc -------------------------------------------------------------------------------- /softpotato/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oliverrdz/EchemSimulations/HEAD/softpotato/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /softpotato/__pycache__/waveform.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oliverrdz/EchemSimulations/HEAD/softpotato/__pycache__/waveform.cpython-38.pyc -------------------------------------------------------------------------------- /cottrell/__main__.py: -------------------------------------------------------------------------------- 1 | from .solver import PlanarDiffusionSolver 2 | from time import time 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | 6 | if __name__=='__main__': 7 | geoms = ['planar','spherical','thin_layer','rde','cylindrical','microband','rce'] 8 | results={} 9 | for g in geoms: 10 | s=PlanarDiffusionSolver(1e-5,1.0,1.0,method='explicit',geometry=g) 11 | t0=time(); s.solve(); t1=time() 12 | results[g]=(s.t_s,s.i_t,t1-t0) 13 | print(g,'time',t1-t0) 14 | 15 | plt.figure() 16 | for g,(t,i,_) in results.items(): 17 | plt.plot(t,i,label=g) 18 | plt.legend(); plt.xlabel('t'); plt.ylabel('i'); plt.show() 19 | -------------------------------------------------------------------------------- /softpotato/mainSP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import waveform as wf 4 | import simulation as sim 5 | import matplotlib.pyplot as plt 6 | 7 | ## Create waveform object 8 | swp = wf.Sweep(Eini=-0.5, Efin=0.5, dE=0.005, ns=4) 9 | wf1 = wf.Construct([swp]) 10 | 11 | # Simulate 12 | sim_FD = sim.FD(wf1) 13 | #sim_BI = sim.BI(wf1) 14 | 15 | plt.figure(1) 16 | plt.plot(wf1.t, wf1.E) 17 | plt.xlabel("$t$ / s") 18 | plt.ylabel("$E$ / V") 19 | plt.grid() 20 | 21 | plt.figure(2) 22 | plt.plot(sim_FD.E, sim_FD.i*1e3, label="FD") 23 | #plt.plot(sim_BI.E, sim_BI.i*1e3, label="BI") 24 | plt.xlabel("$E$ / V") 25 | plt.ylabel("$i$ / mA") 26 | plt.legend() 27 | plt.grid() 28 | 29 | plt.show() 30 | -------------------------------------------------------------------------------- /softpotato/waveform.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import numpy as np 4 | 5 | 6 | 7 | class Sweep: 8 | 9 | def __init__(self, Eini = -0.5, Efin = 0.5, sr = 1, dE = 0.01, ns = 2, tini = 0): 10 | Ewin = abs(Efin-Eini) 11 | tsw = Ewin/sr # total time for one sweep 12 | nt = int(Ewin/dE) 13 | 14 | E = np.array([]) 15 | t = np.linspace(tini, tini+tsw*ns, nt*ns) 16 | 17 | for n in range(1, ns+1): 18 | if (n%2 == 1): 19 | E = np.append(E, np.linspace(Eini, Efin, nt)) 20 | else: 21 | E = np.append(E, np.linspace(Efin, Eini, nt)) 22 | 23 | self.E = E 24 | self.t = t 25 | 26 | 27 | 28 | class Step: 29 | 30 | def __init__(self, Estep = 0.5, tini = 0, ttot = 1, dt = 0.01): 31 | nt = int(ttot/dt) 32 | tfin = tini + ttot 33 | 34 | self.E = np.ones([nt])*Estep 35 | self.t = np.linspace(tini, tfin, nt) 36 | 37 | class Construct: 38 | 39 | def __init__(self, wf): 40 | n = len(wf) 41 | t = np.array([wf[0].t[0]]) 42 | E = np.array([wf[0].E[0]]) 43 | 44 | for i in range(n): 45 | t = np.concatenate([t,wf[i].t+t[-1]]) 46 | E = np.concatenate([E,wf[i].E]) 47 | self.t = t 48 | self.E = E 49 | 50 | -------------------------------------------------------------------------------- /plots.py: -------------------------------------------------------------------------------- 1 | #### Function that creates a potential sweep waveform 2 | ''' 3 | Copyright (C) 2020 Oliver Rodriguez 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU General Public License for more details. 12 | You should have received a copy of the GNU General Public License 13 | along with this program. If not, see . 14 | ''' 15 | #### @author oliverrdz 16 | #### https://oliverrdz.xyz 17 | 18 | import matplotlib.pyplot as plt 19 | import matplotlib 20 | matplotlib.use("TkAgg") 21 | 22 | def plotFormat(): 23 | plt.xticks(fontsize = 14) 24 | plt.yticks(fontsize = 14) 25 | plt.grid() 26 | plt.tight_layout() 27 | 28 | def plot(x, y, xlab, ylab, marker="-", fileName=0): 29 | plt.plot(x, y, marker) 30 | plt.xlabel(xlab, fontsize = 18) 31 | plt.ylabel(ylab, fontsize = 18) 32 | plotFormat() 33 | if fileName: 34 | plt.savefig(fileName) 35 | plt.show() 36 | 37 | def plot2(x1, y1, x2, y2, lab1, lab2, xlab, ylab, marker1="-", marker2 = "-", loc=1): 38 | plt.plot(x1, y1, marker1, label = lab1) 39 | plt.plot(x2, y2, marker2, label = lab2) 40 | plt.xlabel(xlab, fontsize = 18) 41 | plt.ylabel(ylab, fontsize = 18) 42 | plt.legend(loc = loc, fontsize = 14) 43 | plotFormat() 44 | plt.show() 45 | -------------------------------------------------------------------------------- /cottrell/mesh1d.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | class Mesh1D: 4 | """1D mesh for diffusion problems (planar, thin_layer, rde, spherical, cylindrical, microband, rce).""" 5 | 6 | def __init__(self, L_m, NX, x0_m=0.0, grid_type="uniform", 7 | stretch_factor=1.05, geometry="planar"): 8 | self.L_m = L_m 9 | self.NX = NX 10 | self.x0_m = x0_m 11 | self.grid_type = grid_type 12 | self.stretch_factor = stretch_factor 13 | self.geometry = geometry.lower().replace("-", "_") 14 | 15 | if grid_type == "uniform": 16 | self._make_uniform_grid() 17 | elif grid_type == "expanding": 18 | self._make_expanding_grid() 19 | else: 20 | raise ValueError("grid_type must be uniform or expanding") 21 | 22 | self.X = (self.x_m - self.x0_m) / self.L_m 23 | 24 | def _make_uniform_grid(self): 25 | self.x_m = np.linspace(self.x0_m, self.x0_m + self.L_m, self.NX) 26 | self.dx_m = self.x_m[1] - self.x_m[0] 27 | self.dX = self.dx_m / self.L_m 28 | 29 | def _make_expanding_grid(self): 30 | r = self.stretch_factor 31 | N = self.NX 32 | if abs(r-1) < 1e-12: 33 | raise ValueError("stretch_factor cannot be 1") 34 | dx0 = self.L_m * (1 - r) / (1 - r**N) 35 | increments = dx0 * r**np.arange(N) 36 | x_local = np.cumsum(increments) 37 | x_local -= x_local[0] 38 | self.x_m = self.x0_m + x_local 39 | self.dx_m = increments[0] 40 | self.dX = self.dx_m / self.L_m 41 | 42 | def to_um(self): 43 | return self.x_m * 1e6 44 | 45 | def to_cm(self): 46 | return self.x_m * 1e2 47 | -------------------------------------------------------------------------------- /RK4_sp.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import softpotato as sp 4 | 5 | 6 | class Species: 7 | ''' 8 | ''' 9 | def __init__(self, cOb=0, cRb=1e-6, DO=1e-5, DR=1e-5, k0=1e8, alpha=0.5): 10 | self.cOb = cOb 11 | self.cRb = cRb 12 | self.DO = DO 13 | self.DR = DR 14 | self.k0 = k0 15 | self.alpha = alpha 16 | 17 | 18 | class XGrid: 19 | ''' 20 | ''' 21 | def __init__(self, Ageo=1): 22 | self.Ageo = Ageo 23 | self.lamb = 0.45 24 | 25 | def define(self, tgrid, spc): 26 | self.Xmax = 6*np.sqrt(tgrid.nT*self.lamb) 27 | self.dX = np.sqrt(tgrid.dT/self.lamb) 28 | self.nX = int(self.Xmax/self.dX) 29 | self.X = np.linspace(0, self.Xmax, self.nX) 30 | 31 | 32 | class TGrid: 33 | ''' 34 | ''' 35 | def __init__(self): 36 | pass 37 | 38 | def define(self, wf): 39 | self.t = wf.t 40 | self.E = wf.E 41 | self.nT = np.size(self.t) 42 | self.dT = 1/self.nT 43 | 44 | 45 | class Simulate: 46 | ''' 47 | ''' 48 | def __init__(self, wf, xgrid, tgrid, spc): 49 | self.wf = wf 50 | self. xgrid = xgrid 51 | self.tgrid = tgrid 52 | self.spc = spc 53 | sim.i = 0 54 | self.tgrid.define(self.wf) 55 | self.xgrid.define(self.tgrid, self.spc) 56 | 57 | 58 | if __name__ == '__main__': 59 | print('Running from main') 60 | 61 | wf = sp.technique.Sweep() 62 | E_spc = Species.E() 63 | xgrid = XGrid() 64 | tgrid = TGrid() 65 | sim = Simulate(wf, xgrid, tgrid, E_spc) 66 | 67 | 68 | # Plotting 69 | sp.plotting.plot(wf.t, wf.E, xlab='$t$ / s', ylab='$E$ / V', fig=1, show=1) 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EchemScripts 2 | Collection of python scripts to simulate electrochemical problems, some of these are (or will be) used in [Soft Potato](https://softpotato.xyz). The current is approximated with three points, as opposed to the generally used 2-point approximation. 3 | 4 | ### Assumptions 5 | * Cyclic voltammetry (chronoamperometry can be simulated by using the appropriate function from waveforms.py) 6 | * Butler-Volmer kinetics 7 | * Oxidation: only R present at t = 0 unless otherwise stated 8 | 9 | ### Requirements 10 | * Python 3 11 | * Numpy 12 | * Scipy 13 | * Matplotlib 14 | 15 | ### My setup 16 | * Operating system: Manjaro 17 | * CPU: Intel i5-8265U (8) @ 3.900GHz 18 | * Mem: 8 GB 19 | 20 | # List of scripts 21 | ### General 22 | * waveforms.py: functions to generate potential waveforms (potential sweep, potential step, current step) 23 | * plots.py: functions for easy plotting 24 | 25 | ### Electrochemistry simulations 26 | * Explicit finite differences: 27 | * FD-E.py: Simulates an E mechanism with finite differences with only R in solution 28 | * FD-E_OR.py: Simulates an E mechanism with finite differences with O and R in solution 29 | * FD-ECIrrev_ORY.py: Simulates an EC mechanism with finite differences with O and R in solution 30 | * Runge-Kutta 4: 31 | * RK4-E.py: Simulates an E mechanism with Runge-Kutta 4 with only R in solution. Optimized with linear algebra. 32 | * RK4-E_OR.py: Simulates an E mechanism with Runge-Kutta 4 with O and R in solution. Optimized with linear algebra. 33 | * RK4-EC.py: Simulates an EC mechanism with Runge-Kutta 4 with O and R in solution. 34 | * Backwards implicit method: 35 | * BI-ads.py: Surface bound species 36 | * BI-ads_RandCirc.py: Surface bound species with the Randles circuit 37 | * BI-E_RandCirc.py: Solves the Randles circuit for an E mechanism 38 | * Solvers: 39 | * ODEsol-E.py: Simulates an E mechanism using scipy.integrate.solve_ivp. 40 | * BI_banded-E.py: Simulates an E mechanism with scipy.linalg.solve_banded() 41 | * BI_banded-E_RandCirc.py: Solves the Randles circuit for an E mechanism with scipy.linalg.solve_banded() 42 | -------------------------------------------------------------------------------- /BI-ads.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | Created on Tue Jun 23 11:56:38 2020 15 | * R - e- -> O 16 | * Surface bound species 17 | * Butler Volmer 18 | * Backwards implicit 19 | 20 | Simulation time: 0.03 s, with: 21 | * dE = 0.001 (# time elements: 2K) 22 | 23 | @author: oliverrdz 24 | https://oliverrdz.xyz 25 | ''' 26 | 27 | import numpy as np 28 | import plots as p 29 | import waveforms as wf 30 | import time 31 | 32 | start = time.time() 33 | 34 | ## Electrochemistry constants 35 | F = 96485 # C/mol, Faraday constant 36 | R = 8.315 # J/mol K, Gas constant 37 | T = 298 # K, Temperature 38 | FRT = F/(R*T) 39 | 40 | #%% Parameters 41 | 42 | n = 1 # number of electrons 43 | Q0 = 210e-6 # C/cm2, charge density for one monolayer 44 | D = 1e-5 # cm2/s, diffusion coefficient of R 45 | Ageo = 1 # cm2, geometrical area 46 | r = np.sqrt(Ageo/np.pi) # cm, radius of electrode 47 | ks = 1e0 # cm/s, standard rate constant 48 | alpha = 0.5 # transfer coefficient 49 | 50 | # Potential waveform 51 | E0 = 0 # V, standard potential 52 | Eini = -0.5 # V, initial potential 53 | Efin = 0.5 # V, final potential vertex 54 | sr = 1 # V/s, scan rate 55 | ns = 2 # number of sweeps 56 | dE = 0.0001 # V, potential increment. This value has to be small for BI to approximate the circuit properly 57 | 58 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 59 | 60 | g0 = Q0/F # mol/cm2, maximum coverage for 1 monolayer 61 | eps = n*FRT*(E-E0) 62 | kf = ks*np.exp(alpha*eps) 63 | kb = ks*np.exp(-(1-alpha)*eps) 64 | 65 | # Simulation parameters 66 | nt = np.size(t) 67 | dt = t[1] 68 | 69 | Th = np.ones(nt) 70 | 71 | #%% Simulation 72 | for j in range(1,nt): 73 | 74 | # Backwards implicit: 75 | Th[j] = (Th[j-1] + dt*kb[j-1])/(1 + dt*(kf[j-1]+kb[j-1])) 76 | 77 | # Denormalisation 78 | i = -n*F*Ageo*g0*(kb - (kf+kb)*Th) 79 | Q = g0*F*(1-Th) 80 | end = time.time() 81 | print(end-start) 82 | 83 | #%% Plot 84 | p.plot(E, i, "$E$ / V", "$i$ / A") 85 | p.plot(E, Q*1e6, "$E$ / V", "$Q$ / $\mu$C cm$^{-2}$") -------------------------------------------------------------------------------- /BI_banded-E.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.linalg import solve_banded 3 | import plots as p 4 | import waveforms as wf 5 | import time 6 | 7 | start = time.time() 8 | 9 | ## Electrochemistry constants 10 | F = 96485 # C/mol, Faraday constant 11 | R = 8.315 # J/mol K, Gas constant 12 | T = 298 # K, Temperature 13 | FRT = F/(R*T) 14 | 15 | #%% Parameters 16 | 17 | n = 1 # number of electrons 18 | cB = 1e-6 # mol/cm3, bulk concentration of R 19 | D = 1e-5 # cm2/s, diffusion coefficient of R 20 | Ageo = 1 # cm2, geometrical area 21 | r = np.sqrt(Ageo/np.pi) # cm, radius of electrode 22 | ks = 1e8 # cm/s, standard rate constant 23 | alpha = 0.5 # transfer coefficient 24 | 25 | # Potential waveform 26 | E0 = 0 # V, standard potential 27 | Eini = -0.5 # V, initial potential 28 | Efin = 0.5 # V, final potential vertex 29 | sr = 1 # V/s, scan rate 30 | ns = 2 # number of sweeps 31 | dE = 0.0001 # V, potential increment. This value has to be small for BI to approximate the circuit properly 32 | 33 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 34 | 35 | #%% Simulation parameters 36 | delta = np.sqrt(D*t[-1]) # cm, diffusion layer thickness 37 | maxT = 1 # Time normalised by total time 38 | dt = t[1] # t[1] - t[0]; t[0] = 0 39 | dT = dt/t[-1] # normalised time increment 40 | nT = np.size(t) # number of time elements 41 | 42 | maxX = 6*np.sqrt(maxT) # Normalised maximum distance 43 | dX = 2e-3 # normalised distance increment 44 | nX = int(maxX/dX) # number of distance elements 45 | X = np.linspace(0,maxX,nX) # normalised distance array 46 | 47 | K0 = ks*delta/D # Normalised standard rate constant 48 | lamb = dT/dX**2 49 | 50 | # Thomas coefficients 51 | a = -lamb 52 | b = 1 + 2*lamb 53 | g = -lamb 54 | 55 | C = np.ones([nT,nX]) # Initial condition for C 56 | V = np.zeros(nT+1) 57 | i = np.zeros(nT) 58 | 59 | # Constructing ab to use in solve_banded: 60 | ab = np.zeros([3,nX]) 61 | ab[0,2:] = g 62 | ab[1,:] = b 63 | ab[2,:-2] = a 64 | ab[1,0] = 1 65 | ab[1,-1] = 1 66 | 67 | 68 | #%% Simulation 69 | for k in range(0,nT-1): 70 | eps = FRT*(E[k] - E0) 71 | 72 | # Butler-Volmer: 73 | b0 = -(1 +dX*K0*(np.exp((1-alpha)*eps) + np.exp(-alpha*eps))) 74 | g0 = 1 75 | 76 | # Updating ab with the new values 77 | ab[0,1] = g0 78 | ab[1,0] = b0 79 | 80 | # Boundary conditions: 81 | C[k,0] = -dX*K0*np.exp(-alpha*eps) 82 | C[k,-1] = 1 83 | 84 | C[k+1,:] = solve_banded((1,1), ab, C[k,:]) 85 | 86 | # Obtaining faradaic current and solving voltage drop 87 | i[k+1] = n*F*Ageo*D*cB*(-C[k+1,2] + 4*C[k+1,1] - 3*C[k+1,0])/(2*dX*delta) 88 | 89 | # Denormalising: 90 | cR = C*cB 91 | cO = cB - cR 92 | x = X*delta 93 | end = time.time() 94 | print(end-start) 95 | 96 | #%% Plot 97 | p.plot(E, i, "$E$ / V", "$i$ / A") -------------------------------------------------------------------------------- /FD-ECIrrev_ORY.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import plots as p 3 | import waveforms as wf 4 | import time 5 | 6 | start = time.time() 7 | 8 | ## Electrochemistry constants 9 | F = 96485 # C/mol, Faraday constant 10 | R = 8.315 # J/mol K, Gas constant 11 | T = 298 # K, Temperature 12 | FRT = F/(R*T) 13 | 14 | n=1 15 | Ageo=1 16 | cOb=0 17 | cRb=1e-6 18 | DO=1e-5 19 | DR=1e-5 20 | ks=1e8 21 | alpha=0.5 22 | 23 | DY = 1e-5 24 | k1 = 1e-8 # less tan 1e-1 to converge 25 | 26 | # Potential waveform 27 | E0 = 0 # V, standard potential 28 | Eini = -0.5 # V, initial potential 29 | Efin = 0.5 # V, final potential vertex 30 | sr = 1 # V/s, scan rate 31 | ns = 2 # number of sweeps 32 | dE = 0.005 # V, potential increment. This value has to be small for BI to approximate the circuit properly 33 | 34 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) 35 | 36 | DOR = DO/DR 37 | DYR = DY/DR 38 | 39 | #%% Simulation parameters 40 | nT = np.size(t) # number of time elements 41 | dT = 1/nT # adimensional step time 42 | lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 43 | Xmax = 6*np.sqrt(nT*lamb) # Infinite distance 44 | dX = np.sqrt(dT/lamb) # distance increment 45 | nX = int(Xmax/dX) # number of distance elements 46 | 47 | ## Discretisation of variables and initialisation 48 | if cRb == 0: # In case only O present in solution 49 | CR = np.zeros([nT,nX]) 50 | CO = np.ones([nT,nX]) 51 | else: 52 | CR = np.ones([nT,nX]) 53 | CO = np.ones([nT,nX])*cOb/cRb 54 | 55 | CY = np.zeros([nT,nX]) 56 | 57 | X = np.linspace(0,Xmax,nX) # Discretisation of distance 58 | eps = (E-E0)*n*FRT # adimensional potential waveform 59 | delta = np.sqrt(DR*t[-1]) # cm, diffusion layer thickness 60 | K0 = ks*delta/DR # Normalised standard rate constant 61 | K1 = k1*delta/DR 62 | 63 | #%% Simulation 64 | for k in range(1,nT): 65 | # Boundary condition, Butler-Volmer: 66 | CR1kb = CR[k-1,1] 67 | CO1kb = CO[k-1,1] 68 | CR[k,0] = (CR1kb + dX*K0*np.exp(-alpha*eps[k])*(CO1kb + CR1kb/DOR))/( 69 | 1 + dX*K0*(np.exp((1-alpha)*eps[k]) + np.exp(-alpha*eps[k])/DOR)) 70 | CO[k,0] = CO1kb + (CR1kb - CR[k,0])/DOR 71 | 72 | # Solving finite differences: 73 | for j in range(1,nX-1): 74 | CR[k,j] = CR[k-1,j] + lamb*(CR[k-1,j+1] - 2*CR[k-1,j] + CR[k-1,j-1]) 75 | CO[k,j] = CO[k-1,j] + DOR*lamb*(CO[k-1,j+1] - 2*CO[k-1,j] + CO[k-1,j-1]) - \ 76 | dT*K1*CO[k-1,j] #+ dT*K1*CY[k-1,j] 77 | CY[k,j] = CY[k-1,j] + DYR*lamb*(CY[k-1,j+1] - 2*CY[k-1,j] + CY[k-1,j-1]) + \ 78 | dT*K1*CO[k-1,j] #- dT*K1*CO[k-1,j] 79 | 80 | # Denormalising: 81 | if cRb: 82 | I = -CR[:,2] + 4*CR[:,1] - 3*CR[:,0] 83 | D = DR 84 | c = cRb 85 | else: # In case only O present in solution 86 | I = CO[:,2] - 4*CO[:,1] + 3*CO[:,0] 87 | D = DO 88 | c = cOb 89 | i = n*F*Ageo*D*c*I/(2*dX*delta) 90 | 91 | cR = CR*cRb 92 | cO = CO*cOb 93 | x = X*delta 94 | 95 | end = time.time() 96 | print(end-start) 97 | 98 | #%% Plot 99 | p.plot(E, i*1e3, "$E$ / V", "$i$ / mA") 100 | -------------------------------------------------------------------------------- /BI-ads_RandCir.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | Created on Wed Jul 22 16:44:49 2020 15 | * R - e- -> O 16 | * Surface bound species 17 | * Butler Volmer 18 | * Backwards implicit 19 | 20 | Simulation time: 0.12 s, with: 21 | * dE = 0.0001 (# time elements: 2K) 22 | 23 | @author: oliverrdz 24 | https://oliverrdz.xyz 25 | ''' 26 | 27 | import numpy as np 28 | from scipy.integrate import cumtrapz 29 | import plots as p 30 | import waveforms as wf 31 | import time 32 | 33 | start = time.time() 34 | 35 | ## Electrochemistry constants 36 | F = 96485 # C/mol, Faraday constant 37 | R = 8.315 # J/mol K, Gas constant 38 | T = 298 # K, Temperature 39 | FRT = F/(R*T) 40 | 41 | #%% Parameters 42 | 43 | n = 1 # number of electrons 44 | Q0 = 210e-6 # C/cm2, charge density for one monolayer 45 | D = 1e-5 # cm2/s, diffusion coefficient of R 46 | Ageo = 1 # cm2, geometrical area 47 | r = np.sqrt(Ageo/np.pi) # cm, radius of electrode 48 | ks = 1e0 # cm/s, standard rate constant 49 | alpha = 0.5 # transfer coefficient 50 | 51 | Rf = 5 # Roughness factor 52 | C = 20e-6 # F/cm2, specific capacitance 53 | x = 0.1 # cm, Luggin electrode distance 54 | kapa = 0.0632 # Ohm-1 cm-1, conductivity for 0.5 M NaCl 55 | Cdl = Ageo*Rf*C # F, double layer capacitance 56 | Ru = x/(kapa*Ageo) # Ohms, solution resistance 57 | 58 | # Potential waveform 59 | E0 = 0 # V, standard potential 60 | Eini = -0.5 # V, initial potential 61 | Efin = 0.5 # V, final potential vertex 62 | sr = 1 # V/s, scan rate 63 | ns = 2 # number of sweeps 64 | dE = 0.0001 # V, potential increment. This value has to be small for BI to approximate the circuit properly 65 | 66 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 67 | 68 | g0 = Q0/F # mol/cm2, maximum coverage for 1 monolayer 69 | 70 | # Simulation parameters 71 | nt = np.size(t) 72 | dt = t[1] 73 | 74 | Th = np.ones(nt) 75 | V = np.zeros(nt) 76 | V[0] = E[0] 77 | 78 | #%% Simulation 79 | for j in range(1,nt): 80 | 81 | # iR drop makes the applied potential to be V, not E: 82 | eps = n*FRT*(V[j-1]-E0) 83 | kf = ks*np.exp(alpha*eps) 84 | kb = ks*np.exp(-(1-alpha)*eps) 85 | 86 | # Backwards implicit: 87 | Th[j] = (Th[j-1] + dt*kb)/(1 + dt*(kf+kb)) 88 | V[j] = (V[j-1] + (dt/Cdl)*(E[j]/Ru +n*F*Ageo*g0*(kb-(kf+kb)*Th[j])))/(1 + dt/(Cdl*Ru)) 89 | 90 | # Denormalisation 91 | i = (E - V)/Ru # The current is obtained from the Randles circuit 92 | Q = cumtrapz(i, t, initial=0) 93 | end = time.time() 94 | print(end-start) 95 | 96 | #%% Plot 97 | p.plot(E, i, "$E$ / V", "$i$ / A") 98 | p.plot(E, Q*1e6, "$E$ / V", "$Q$ / $\mu$C cm$^{-2}$") -------------------------------------------------------------------------------- /RK4-EC.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.sparse import diags 3 | import plots as p 4 | import waveforms as wf 5 | import time 6 | 7 | start = time.time() 8 | 9 | ## Electrochemistry constants 10 | F = 96485 # C/mol, Faraday constant 11 | R = 8.315 # J/mol K, Gas constant 12 | T = 298 # K, Temperature 13 | FRT = F/(R*T) 14 | 15 | n=1 16 | Ageo=1 17 | cOb=0 18 | cRb=1e-6 19 | DO=1e-5 20 | DR=1e-5 21 | ks=1e8 22 | alpha=0.5 23 | 24 | DP = 1e-5 25 | kc = 1e1 # less tan 1e-1 to converge 26 | 27 | # Potential waveform 28 | E0 = 0 # V, standard potential 29 | Eini = -0.5 # V, initial potential 30 | Efin = 0.5 # V, final potential vertex 31 | sr = 1 # V/s, scan rate 32 | ns = 2 # number of sweeps 33 | dE = 0.005 # V, potential increment. This value has to be small for BI to approximate the circuit properly 34 | 35 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) 36 | 37 | DOR = DO/DR 38 | #DPR = DP/DR 39 | 40 | #%% Simulation parameters 41 | nT = np.size(t) # number of time elements 42 | dT = 1/nT # adimensional step time 43 | lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 44 | Xmax = 6*np.sqrt(nT*lamb) # Infinite distance 45 | dX = np.sqrt(dT/lamb) # distance increment 46 | nX = int(Xmax/dX) # number of distance elements 47 | 48 | ## Discretisation of variables and initialisation 49 | if cRb == 0: # In case only O present in solution 50 | CR = np.zeros([nT,nX]) 51 | CO = np.ones([nT,nX]) 52 | else: 53 | CR = np.ones([nT,nX]) 54 | CO = np.ones([nT,nX])*cOb/cRb 55 | 56 | CP = np.zeros([nT,nX]) 57 | 58 | X = np.linspace(0,Xmax,nX) # Discretisation of distance 59 | eps = (E-E0)*n*FRT # adimensional potential waveform 60 | delta = np.sqrt(DR*t[-1]) # cm, diffusion layer thickness 61 | Ke = ks*delta/DR # Normalised standard rate constant 62 | Kc = kc*delta/DR 63 | 64 | 65 | Cb = np.ones(nX-1) # Cbefore 66 | Cp = -2*np.ones(nX) # Cpresent 67 | Ca = np.ones(nX-1) # Cafter 68 | A = diags([Cb,Cp,Ca], [-1,0,1]).toarray()/(dX**2) # - dT*K*Cp 69 | A[0,:] = np.zeros(nX) 70 | A[0,0] = 1 # Initial condition 71 | print(A) 72 | 73 | def fun(y, mech='E'): 74 | if mech == 'E': 75 | return np.dot(A,y) 76 | else: 77 | return np.dot(A,y) - dT*Kc*y 78 | 79 | def RK4(y, mech): 80 | k1 = fun(y, mech) 81 | k2 = fun(y+dT*k1/2, mech) 82 | k3 = fun(y+dT*k2/2, mech) 83 | k4 = fun(y+dT*k3, mech) 84 | return y + (dT/6)*(k1 + 2*k2 + 2*k3 + k4) 85 | 86 | #%% Simulation 87 | for k in range(1,nT): 88 | # Boundary condition, Butler-Volmer: 89 | CR1kb = CR[k-1,1] 90 | CO1kb = CO[k-1,1] 91 | CR[k,0] = (CR1kb + dX*Ke*np.exp(-alpha*eps[k])*(CO1kb + CR1kb/DOR))/( 92 | 1 + dX*Ke*(np.exp((1-alpha)*eps[k]) + np.exp(-alpha*eps[k])/DOR)) 93 | CO[k,0] = CO1kb + (CR1kb - CR[k,0])/DOR 94 | # Runge-Kutta 4: 95 | CR[k,1:-1] = RK4(CR[k-1,:], 'E')[1:-1] 96 | CO[k,1:-1] = RK4(CO[k-1,:], 'EC')[1:-1] 97 | 98 | # Denormalising: 99 | if cRb: 100 | I = -CR[:,2] + 4*CR[:,1] - 3*CR[:,0] 101 | D = DR 102 | c = cRb 103 | else: # In case only O present in solution 104 | I = CO[:,2] - 4*CO[:,1] + 3*CO[:,0] 105 | D = DO 106 | c = cOb 107 | i = n*F*Ageo*D*c*I/(2*dX*delta) 108 | 109 | cR = CR*cRb 110 | cO = CO*cOb 111 | x = X*delta 112 | 113 | end = time.time() 114 | print(end-start) 115 | 116 | #%% Plot 117 | p.plot(E, i*1e3, "$E$ / V", "$i$ / mA") 118 | -------------------------------------------------------------------------------- /FD-E.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | Created on Wed Jul 22 15:07:06 2020 15 | * R - e- -> O 16 | * Diffusion, E mechanism 17 | * Butler Volmer 18 | * Explicit finite differences 19 | 20 | Simulation time: 16 s, with: 21 | * dE = 0.001 (# time elements: 2K) 22 | * dX (fixed) = 0.033 (# distance elements: 5.4K) 23 | 24 | @author: oliverrdz 25 | https://oliverrdz.xyz 26 | ''' 27 | 28 | import numpy as np 29 | import plots as p 30 | import waveforms as wf 31 | import time 32 | 33 | start = time.time() 34 | 35 | ## Electrochemistry constants 36 | F = 96485 # C/mol, Faraday constant 37 | R = 8.315 # J/mol K, Gas constant 38 | T = 298 # K, Temperature 39 | FRT = F/(R*T) 40 | 41 | #%% Parameters 42 | 43 | n = 1 # number of electrons 44 | cB = 1e-6 # mol/cm3, bulk concentration of R 45 | D = 1e-5 # cm2/s, diffusion coefficient of R 46 | Ageo = 1 # cm2, geometrical area 47 | r = np.sqrt(Ageo/np.pi) # cm, radius of electrode 48 | ks = 1e-3 # cm/s, standard rate constant 49 | alpha = 0.5 # transfer coefficient 50 | 51 | # Potential waveform 52 | E0 = 0 # V, standard potential 53 | Eini = -0.5 # V, initial potential 54 | Efin = 0.5 # V, final potential vertex 55 | sr = 1 # V/s, scan rate 56 | ns = 2 # number of sweeps 57 | dE = 0.01 # V, potential increment. This value has to be small for BI to approximate the circuit properly 58 | 59 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 60 | 61 | #%% Simulation parameters 62 | nT = np.size(t) # number of time elements 63 | dT = 1/nT # adimensional step time 64 | lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 65 | Xmax = 6*np.sqrt(nT*lamb) # Infinite distance 66 | dX = np.sqrt(dT/lamb) # distance increment 67 | nX = int(Xmax/dX) # number of distance elements 68 | 69 | ## Discretisation of variables and initialisation 70 | C = np.ones([nT,nX]) # Initial condition for R 71 | X = np.linspace(0,Xmax,nX) # Discretisation of distance 72 | eps = (E-E0)*n*FRT # adimensional potential waveform 73 | delta = np.sqrt(D*t[-1]) # cm, diffusion layer thickness 74 | K0 = ks*delta/D # Normalised standard rate constant 75 | 76 | #%% Simulation 77 | for k in range(1,nT): 78 | # Boundary condition, Butler-Volmer: 79 | C[k,0] = (C[k-1,1] + dX*K0*np.exp(-alpha*eps[k]))/(1+dX*K0*(np.exp((1-alpha)*eps[k])+np.exp(-alpha*eps[k]))) 80 | 81 | # Solving finite differences: 82 | for j in range(1,nX-1): 83 | C[k,j] = C[k-1,j] + lamb*(C[k-1,j+1] - 2*C[k-1,j] + C[k-1,j-1]) 84 | 85 | # Denormalising: 86 | i = n*F*Ageo*D*cB*(-C[:,2] + 4*C[:,1] - 3*C[:,0])/(2*dX*delta) 87 | cR = C*cB 88 | cO = cB - cR 89 | x = X*delta 90 | end = time.time() 91 | print(end-start) 92 | 93 | #%% Plot 94 | p.plot(E, i, "$E$ / V", "$i$ / A") 95 | p.plot2(x, cR[-1,:]*1e6, x, cO[-1,:]*1e6, "[R]", "[O]", "x / cm", "c($t_{end}$,$x$=0) / mM") 96 | -------------------------------------------------------------------------------- /FD-E_OR.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | Created on Wed Jul 22 15:07:06 2020 15 | * R - e- -> O 16 | * Diffusion, E mechanism 17 | * Butler Volmer 18 | * Explicit finite differences 19 | 20 | @author: oliverrdz 21 | https://oliverrdz.xyz 22 | ''' 23 | 24 | import numpy as np 25 | import plots as p 26 | import waveforms as wf 27 | 28 | ## Electrochemistry constants 29 | F = 96485 # C/mol, Faraday constant 30 | R = 8.315 # J/mol K, Gas constant 31 | T = 298 # K, Temperature 32 | FRT = F/(R*T) 33 | 34 | n=1 35 | Ageo = 0.0314 36 | cOb=0#1e-6 37 | cRb=1e-6 38 | DO=3.25e-5 39 | DR=3.25e-5 40 | ks=1e8 41 | alpha=0.5 42 | 43 | # Potential waveform 44 | E0 = 0 # V, standard potential 45 | Eini = -0.5 # V, initial potential 46 | Efin = 0.5 # V, final potential vertex 47 | sr = 0.1 # V/s, scan rate 48 | ns = 2 # number of sweeps 49 | dE = 0.01 # V, potential increment. This value has to be small for BI to approximate the circuit properly 50 | 51 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) 52 | 53 | DOR = DO/DR 54 | 55 | #%% Simulation parameters 56 | nT = np.size(t) # number of time elements 57 | dT = 1/nT # adimensional step time 58 | lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 59 | Xmax = 6*np.sqrt(nT*lamb) # Infinite distance 60 | dX = np.sqrt(dT/lamb) # distance increment 61 | nX = int(Xmax/dX) # number of distance elements 62 | 63 | ## Discretisation of variables and initialisation 64 | if cRb == 0: # In case only O present in solution 65 | CR = np.zeros([nT,nX]) 66 | CO = np.ones([nT,nX]) 67 | else: 68 | CR = np.ones([nT,nX]) 69 | CO = np.ones([nT,nX])*cOb/cRb 70 | 71 | 72 | X = np.linspace(0,Xmax,nX) # Discretisation of distance 73 | eps = (E-E0)*n*FRT # adimensional potential waveform 74 | delta = np.sqrt(DR*t[-1]) # cm, diffusion layer thickness 75 | K0 = ks*delta/DR # Normalised standard rate constant 76 | 77 | #%% Simulation 78 | for k in range(1,nT): 79 | # Boundary condition, Butler-Volmer: 80 | CR1kb = CR[k-1,1] 81 | CO1kb = CO[k-1,1] 82 | CR[k,0] = (CR1kb + dX*K0*np.exp(-alpha*eps[k])*(CO1kb + CR1kb/DOR))/( 83 | 1 + dX*K0*(np.exp((1-alpha)*eps[k]) + np.exp(-alpha*eps[k])/DOR)) 84 | CO[k,0] = CO1kb + (CR1kb - CR[k,0])/DOR 85 | 86 | # Solving finite differences: 87 | for j in range(1,nX-1): 88 | CR[k,j] = CR[k-1,j] + lamb*(CR[k-1,j+1] - 2*CR[k-1,j] + CR[k-1,j-1]) 89 | CO[k,j] = CO[k-1,j] + DOR*lamb*(CO[k-1,j+1] - 2*CO[k-1,j] + CO[k-1,j-1]) 90 | 91 | # Denormalising: 92 | if cRb: 93 | I = -CR[:,2] + 4*CR[:,1] - 3*CR[:,0] 94 | D = DR 95 | c = cRb 96 | else: # In case only O present in solution 97 | I = CO[:,2] - 4*CO[:,1] + 3*CO[:,0] 98 | D = DO 99 | c = cOb 100 | i = n*F*Ageo*D*c*I/(2*dX*delta) 101 | 102 | cR = CR*cRb 103 | cO = CO*cOb 104 | x = X*delta 105 | 106 | #%% Plot 107 | p.plot(E, i*1e6, "$E$ / V", "$i$ / $\mu$A") 108 | -------------------------------------------------------------------------------- /RK4-EC_R.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | Created on Wed Jul 22 15:07:06 2020 15 | * R - e- -> O 16 | * Diffusion, E mechanism 17 | * Butler Volmer 18 | * Runge Kutta 4 19 | 20 | @author: oliverrdz 21 | https://oliverrdz.xyz 22 | ''' 23 | 24 | import numpy as np 25 | from scipy.sparse import diags 26 | import plots as p 27 | import waveforms as wf 28 | import time 29 | 30 | start = time.time() 31 | 32 | ## Electrochemistry constants 33 | F = 96485 # C/mol, Faraday constant 34 | R = 8.315 # J/mol K, Gas constant 35 | T = 298 # K, Temperature 36 | FRT = F/(R*T) 37 | 38 | #%% Parameters 39 | 40 | n = 1 # number of electrons 41 | cB = 1e-6 # mol/cm3, bulk concentration of R 42 | D = 1e-5 # cm2/s, diffusion coefficient of R 43 | Ageo = 1 # cm2, geometrical area 44 | r = np.sqrt(Ageo/np.pi) # cm, radius of electrode 45 | ks = 1e-3 # cm/s, standard rate constant 46 | alpha = 0.5 # transfer coefficient 47 | 48 | # Potential waveform 49 | E0 = 0 # V, standard potential 50 | Eini = -0.5 # V, initial potential 51 | Efin = 0.5 # V, final potential vertex 52 | sr = 1 # V/s, scan rate 53 | ns = 2 # number of sweeps 54 | dE = 0.01 # V, potential increment. This value has to be small for BI to approximate the circuit properly 55 | 56 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 57 | 58 | #%% Simulation parameters 59 | nT = np.size(t) # number of time elements 60 | dT = 1/nT # adimensional step time 61 | lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 62 | Xmax = 6*np.sqrt(nT*lamb) # Infinite distance 63 | dX = np.sqrt(dT/lamb) # distance increment 64 | nX = int(Xmax/dX) # number of distance elements 65 | 66 | ## Discretisation of variables and initialisation 67 | C = np.ones([nT,nX]) # Initial condition for R 68 | X = np.linspace(0,Xmax,nX) # Discretisation of distance 69 | eps = (E-E0)*n*FRT # adimensional potential waveform 70 | delta = np.sqrt(D*t[-1]) # cm, diffusion layer thickness 71 | K0 = ks*delta/D # Normalised standard rate constant 72 | 73 | Cb = np.ones(nX-1) # Cbefore 74 | Cp = -2*np.ones(nX) # Cpresent 75 | Ca = np.ones(nX-1) # Cafter 76 | A = diags([Cb,Cp,Ca], [-1,0,1]).toarray()/(dX**2) 77 | A[0,:] = np.zeros(nX) 78 | A[0,0] = 1 # Initial condition 79 | 80 | def RK4(y): 81 | k1 = fun(y) 82 | k2 = fun(y+dT*k1/2) 83 | k3 = fun(y+dT*k2/2) 84 | k4 = fun(y+dT*k3) 85 | return y + (dT/6)*(k1 + 2*k2 + 2*k3 + k4) 86 | 87 | def fun(y): 88 | return np.dot(A,y) 89 | 90 | #%% Simulation 91 | for k in range(1,nT): 92 | #print(nT-k) 93 | # Boundary condition, Butler-Volmer: 94 | C[k,0] = (C[k-1,1] + dX*K0*np.exp(-alpha*eps[k]))/(1+dX*K0*(np.exp((1-alpha)*eps[k])+np.exp(-alpha*eps[k]))) 95 | C[k,1:-1] = RK4(C[k-1,:])[1:-1]#, A[:-1,:-1]) 96 | 97 | # Denormalising: 98 | i = n*F*Ageo*D*cB*(-C[:,2] + 4*C[:,1] - 3*C[:,0])/(2*dX*delta) 99 | cR = C*cB 100 | cO = cB - cR 101 | x = X*delta 102 | end = time.time() 103 | print(end-start) 104 | 105 | #%% Plot 106 | p.plot(E, i, "$E$ / V", "$i$ / A") 107 | #p.plot2(x, cR[-1,:]*1e6, x, cO[-1,:]*1e6, "[R]", "[O]", "x / cm", "c($t_{end}$,$x$=0) / mM") 108 | -------------------------------------------------------------------------------- /ODEsol-E.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | Created on Wed Jul 22 15:07:06 2020 15 | * R - e- -> O 16 | * Diffusion, E mechanism 17 | * Butler Volmer 18 | * solve_ivp from scipy 19 | 20 | @author: oliverrdz 21 | https://oliverrdz.xyz 22 | ''' 23 | 24 | import numpy as np 25 | import matplotlib.pyplot as plt 26 | from scipy.sparse import diags 27 | from scipy.integrate import solve_ivp 28 | import softpotato as sp 29 | import time 30 | 31 | start = time.time() 32 | 33 | ## Electrochemistry constants 34 | F = 96485 # C/mol, Faraday constant 35 | R = 8.315 # J/mol K, Gas constant 36 | T = 298 # K, Temperature 37 | FRT = F/(R*T) 38 | 39 | #%% Parameters 40 | 41 | n = 1 # number of electrons 42 | cB = 1e-6 # mol/cm3, bulk concentration of R 43 | D = 1e-5 # cm2/s, diffusion coefficient of R 44 | Ageo = 1 # cm2, geometrical area 45 | r = np.sqrt(Ageo/np.pi) # cm, radius of electrode 46 | ks = 1e3 # cm/s, standard rate constant 47 | alpha = 0.5 # transfer coefficient 48 | 49 | # Potential waveform 50 | E0 = 0 # V, standard potential 51 | Eini = -0.5 # V, initial potential 52 | Efin = 0.5 # V, final potential vertex 53 | sr = 1 # V/s, scan rate 54 | ns = 2 # number of sweeps 55 | dE = 0.001 # V, potential increment. This value has to be small for BI to approximate the circuit properly 56 | 57 | wf = sp.technique.Sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 58 | E = wf.E 59 | t = wf.t 60 | 61 | #%% Simulation parameters 62 | nT = np.size(t) # number of time elements 63 | dT = 1/nT # adimensional step time 64 | lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 65 | Xmax = 6*np.sqrt(nT*lamb) # Infinite distance 66 | dX = np.sqrt(dT/lamb) # distance increment 67 | nX = int(Xmax/dX) # number of distance elements 68 | 69 | ## Discretisation of variables and initialisation 70 | C = np.ones([nT,nX]) # Initial condition for R 71 | X = np.linspace(0,Xmax,nX) # Discretisation of distance 72 | eps = (E-E0)*n*FRT # adimensional potential waveform 73 | delta = np.sqrt(D*t[-1]) # cm, diffusion layer thickness 74 | K0 = ks*delta/D # Normalised standard rate constant 75 | 76 | Cb = np.ones(nX-1) # Cbefore 77 | Cp = -2*np.ones(nX) # Cpresent 78 | Ca = np.ones(nX-1) # Cafter 79 | A = diags([Cb,Cp,Ca], [-1,0,1]).toarray()/(dX**2) 80 | A[0,:] = np.zeros(nX) 81 | A[0,0] = 1 82 | 83 | def fun(t,y): 84 | return np.dot(A,y) 85 | 86 | #%% Simulation 87 | for k in range(1,nT): 88 | #print(nT-k) 89 | # Boundary condition, Butler-Volmer: 90 | C[k,0] = (C[k-1,1] + dX*K0*np.exp(-alpha*eps[k]))/(1+dX*K0*(np.exp((1-alpha)*eps[k])+np.exp(-alpha*eps[k]))) 91 | sol = solve_ivp(fun, [0,dT], C[k-1,:], t_eval=[dT], method='RK45') 92 | C[k,1:-1] = sol.y[1:-1,0] 93 | 94 | # Denormalising: 95 | i = n*F*Ageo*D*cB*(-C[:,2] + 4*C[:,1] - 3*C[:,0])/(2*dX*delta) 96 | cR = C*cB 97 | cO = cB - cR 98 | x = X*delta 99 | end = time.time() 100 | print(end-start) 101 | 102 | # Simulating with softpotato 103 | sim = sp.simulate.E(wf, n, Ageo, 0, 0, cB, D, D, ks, alpha) 104 | sim.run() 105 | 106 | # Randles Sevcik 107 | rs = sp.calculate.Macro(n, Ageo, cB, D) 108 | irs = rs.RandlesSevcik(np.array([sr]))*np.ones(E.size) 109 | #%% Plot 110 | plt.figure(1) 111 | plt.plot(E, irs*1e3) 112 | plt.plot(E, i*1e3, label='RK4') 113 | plt.plot(E, sim.i*1e3, label='softpotato') 114 | sp.plotting.format(xlab='$E$ / V', ylab='$i$ / mA', legend=[1], show=1) 115 | -------------------------------------------------------------------------------- /RK4-E.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | Created on Wed Jul 22 15:07:06 2020 15 | * R - e- -> O 16 | * Diffusion, E mechanism 17 | * Butler Volmer 18 | * Runge Kutta 4 19 | 20 | @author: oliverrdz 21 | https://oliverrdz.xyz 22 | ''' 23 | 24 | import numpy as np 25 | from scipy.sparse import diags 26 | import softpotato as sp 27 | import matplotlib.pyplot as plt 28 | import time 29 | 30 | start = time.time() 31 | 32 | ## Electrochemistry constants 33 | F = 96485 # C/mol, Faraday constant 34 | R = 8.315 # J/mol K, Gas constant 35 | T = 298 # K, Temperature 36 | FRT = F/(R*T) 37 | 38 | #%% Parameters 39 | 40 | n = 1 # number of electrons 41 | cB = 1e-6 # mol/cm3, bulk concentration of R 42 | D = 1e-5 # cm2/s, diffusion coefficient of R 43 | Ageo = 1 # cm2, geometrical area 44 | r = np.sqrt(Ageo/np.pi) # cm, radius of electrode 45 | ks = 1e3 # cm/s, standard rate constant 46 | alpha = 0.5 # transfer coefficient 47 | 48 | # Potential waveform 49 | E0 = 0 # V, standard potential 50 | Eini = -0.5 # V, initial potential 51 | Efin = 0.5 # V, final potential vertex 52 | sr = 1 # V/s, scan rate 53 | ns = 2 # number of sweeps 54 | dE = 0.01 # V, potential increment. This value has to be small for BI to approximate the circuit properly 55 | 56 | wf = sp.technique.Sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 57 | E = wf.E 58 | t = wf.t 59 | 60 | #%% Simulation parameters 61 | nT = np.size(t) # number of time elements 62 | dT = 1/nT # adimensional step time 63 | lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 64 | Xmax = 6*np.sqrt(nT*lamb) # Infinite distance 65 | dX = np.sqrt(dT/lamb) # distance increment 66 | nX = int(Xmax/dX) # number of distance elements 67 | 68 | ## Discretisation of variables and initialisation 69 | C = np.ones([nT,nX]) # Initial condition for R 70 | X = np.linspace(0,Xmax,nX) # Discretisation of distance 71 | eps = (E-E0)*n*FRT # adimensional potential waveform 72 | delta = np.sqrt(D*t[-1]) # cm, diffusion layer thickness 73 | K0 = ks*delta/D # Normalised standard rate constant 74 | 75 | Cb = np.ones(nX-1) # Cbefore 76 | Cp = -2*np.ones(nX) # Cpresent 77 | Ca = np.ones(nX-1) # Cafter 78 | A = diags([Cb,Cp,Ca], [-1,0,1]).toarray()/(dX**2) 79 | A[0,:] = np.zeros(nX) 80 | A[0,0] = 1 # Initial condition 81 | 82 | def RK4(y): 83 | k1 = fun(y) 84 | k2 = fun(y+dT*k1/2) 85 | k3 = fun(y+dT*k2/2) 86 | k4 = fun(y+dT*k3) 87 | return y + (dT/6)*(k1 + 2*k2 + 2*k3 + k4) 88 | 89 | def fun(y): 90 | return np.dot(A,y) 91 | 92 | 93 | #%% Simulation 94 | for k in range(1,nT): 95 | #print(nT-k) 96 | # Boundary condition, Butler-Volmer: 97 | C[k,0] = (C[k-1,1] + dX*K0*np.exp(-alpha*eps[k]))/(1+dX*K0*(np.exp((1-alpha)*eps[k])+np.exp(-alpha*eps[k]))) 98 | C[k,1:-1] = RK4(C[k-1,:])[1:-1]#, A[:-1,:-1]) 99 | 100 | # Denormalising: 101 | i = n*F*Ageo*D*cB*(-C[:,2] + 4*C[:,1] - 3*C[:,0])/(2*dX*delta) 102 | cR = C*cB 103 | cO = cB - cR 104 | x = X*delta 105 | end = time.time() 106 | print(end-start) 107 | 108 | # Simulating with softpotato 109 | sim = sp.simulate.E(wf, n, Ageo, 0, 0, cB, D, D, ks, alpha) 110 | sim.run() 111 | 112 | # Randles Sevcik 113 | rs = sp.calculate.Macro(n, Ageo, cB, D) 114 | irs = rs.RandlesSevcik(np.array([sr]))*np.ones(E.size) 115 | 116 | #%% Plot 117 | #sp.plotting.plot(E, i*1e3, ylab='mA', fig=1, show=1) 118 | plt.figure(1) 119 | plt.plot(E, irs*1e3) 120 | plt.plot(E, i*1e3, label='RK4') 121 | plt.plot(E, sim.i*1e3, label='softpotato') 122 | sp.plotting.format(xlab='$E$ / V', ylab='$i$ / mA', legend=[1], show=1) 123 | -------------------------------------------------------------------------------- /BI-E_RandCirc.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | 15 | Created on Thu Jul 16 10:44:28 2020 16 | * R - e- -> O 17 | * Diffusion with Randless circuit 18 | * Butler Volmer 19 | * Backwards implicit 20 | 21 | Simulation time: 122 s, with: 22 | * dE = 0.0001 (# time elements: 20K) 23 | * dX = 2e-3 (# distance elements: 3K) 24 | 25 | @author: oliverrdz 26 | https://oliverrdz.xyz 27 | """ 28 | 29 | import numpy as np 30 | import plots as p 31 | import waveforms as wf 32 | import time 33 | 34 | start = time.time() 35 | 36 | ## Electrochemistry constants 37 | F = 96485 # C/mol, Faraday constant 38 | R = 8.315 # J/mol K, Gas constant 39 | T = 298 # K, Temperature 40 | FRT = F/(R*T) 41 | 42 | #%% Parameters 43 | 44 | n = 1 # number of electrons 45 | cB = 1e-6 # mol/cm3, bulk concentration of R 46 | D = 1e-5 # cm2/s, diffusion coefficient of R 47 | Ageo = 1 # cm2, geometrical area 48 | r = np.sqrt(Ageo/np.pi) # cm, radius of electrode 49 | ks = 1e-3 # cm/s, standard rate constant 50 | alpha = 0.5 # transfer coefficient 51 | 52 | Rf = 5 # Roughness factor 53 | C = 20e-6 # F/cm2, specific capacitance 54 | x = 0.1 # cm, Luggin electrode distance 55 | kapa = 0.0632 # Ohm-1 cm-1, conductivity for 0.5 M NaCl 56 | Cdl = Ageo*Rf*C # F, double layer capacitance 57 | Ru = x/(kapa*Ageo) # Ohms, solution resistance 58 | 59 | # Potential waveform 60 | E0 = 0 # V, standard potential 61 | Eini = -0.5 # V, initial potential 62 | Efin = 0.5 # V, final potential vertex 63 | sr = 1 # V/s, scan rate 64 | ns = 2 # number of sweeps 65 | dE = 0.0001 # V, potential increment. This value has to be small for BI to approximate the circuit properly 66 | 67 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 68 | 69 | #%% Simulation parameters 70 | delta = np.sqrt(D*t[-1]) # cm, diffusion layer thickness 71 | maxT = 1 # Time normalised by total time 72 | dt = t[1] # t[1] - t[0]; t[0] = 0 73 | dT = dt/t[-1] # normalised time increment 74 | nT = np.size(t) # number of time elements 75 | 76 | maxX = 6*np.sqrt(maxT) # Normalised maximum distance 77 | dX = 2e-3 # normalised distance increment 78 | nX = int(maxX/dX) # number of distance elements 79 | X = np.linspace(0,maxX,nX) # normalised distance array 80 | 81 | K0 = ks*delta/D # Normalised standard rate constant 82 | lamb = dT/dX**2 83 | 84 | # Thomas coefficients 85 | a = -lamb 86 | b = 1 + 2*lamb 87 | g = -lamb 88 | 89 | g_mod = np.zeros(nX) 90 | C = np.ones([nT,nX]) # Initial condition for C 91 | V = np.zeros(nT+1) 92 | iF = np.zeros(nT) 93 | 94 | V[0] = E[0] 95 | 96 | #%% Simulation 97 | for k in range(0,nT-1): 98 | eps = FRT*(V[k] - E0) 99 | 100 | g_mod[0] = 1/(-1 -dX*K0*(np.exp((1-alpha)*eps) + np.exp(-alpha*eps))) 101 | C[k,0] = -dX*K0*np.exp(-alpha*eps)/(-1 -dX*K0*(np.exp((1-alpha)*eps) + np.exp(-alpha*eps))) 102 | 103 | for i in range(1,nX): 104 | C[k,i] = (C[k,i] - C[k,i-1]*a)/(b - g_mod[i-1]*a) 105 | g_mod[i] = g/(b - g_mod[i-1]*a) 106 | 107 | C[k,nX-1] = 1 # Outer boundary condition 108 | for i in range(nX-2,-1,-1): 109 | C[k,i] = C[k,i] - g_mod[i]*C[k,i+1] 110 | 111 | iF[k] = n*F*Ageo*D*cB*(-C[k,2] + 4*C[k,1] - 3*C[k,0])/(2*dX*delta) 112 | V[k+1] = (V[k] + (t[1]/Cdl)*(E[k]/Ru -iF[k]))/(1 + t[1]/(Cdl*Ru)) 113 | C[k+1,:] = C[k,:] 114 | 115 | i = (E-V[:-1])/Ru 116 | end = time.time() 117 | 118 | # Denormalising: 119 | cR = C*cB 120 | cO = cB - cR 121 | x = X*delta 122 | end = time.time() 123 | print(end-start) 124 | 125 | #%% Plot 126 | p.plot(E, i, "$E$ / V", "$i$ / A") 127 | p.plot2(x, cR[-1,:]*1e6, x, cO[-1,:]*1e6, "[R]", "[O]", "x / cm", "c($t_{end}$,$x$=0) / mM") 128 | -------------------------------------------------------------------------------- /RK4-E_OR.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | Created on Wed Jul 22 15:07:06 2020 15 | * R - e- -> O 16 | * Diffusion, E mechanism 17 | * Butler Volmer 18 | * Runge Kutta 4 19 | 20 | @author: oliverrdz 21 | https://oliverrdz.xyz 22 | ''' 23 | 24 | import numpy as np 25 | from scipy.sparse import diags 26 | import plots as p 27 | import waveforms as wf 28 | import time 29 | 30 | start = time.time() 31 | 32 | ## Electrochemistry constants 33 | F = 96485 # C/mol, Faraday constant 34 | R = 8.315 # J/mol K, Gas constant 35 | T = 298 # K, Temperature 36 | FRT = F/(R*T) 37 | 38 | #%% Parameters 39 | 40 | n = 1 # number of electrons 41 | cOb = 0#1e-6 42 | cRb = 1e-6 # mol/cm3, bulk concentration of R 43 | DO = 3.25e-5#1e-5 # cm2/s, diffusion coefficient of R 44 | DR = 3.25e-5#1e-5 45 | Ageo = 0.03145 # cm2, geometrical area 46 | ks = 1e3 # cm/s, standard rate constant 47 | alpha = 0.5 # transfer coefficient 48 | 49 | # Potential waveform 50 | E0 = 0 # V, standard potential 51 | Eini = -0.5 # V, initial potential 52 | Efin = 0.5 # V, final potential vertex 53 | sr = 0.1 # V/s, scan rate 54 | ns = 2 # number of sweeps 55 | dE = 0.005 # V, potential increment. This value has to be small for BI to approximate the circuit properly 56 | DOR = DO/DR 57 | 58 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 59 | 60 | #%% Simulation parameters 61 | nT = np.size(t) # number of time elements 62 | dT = 1/nT # adimensional step time 63 | lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 64 | Xmax = 6*np.sqrt(nT*lamb) # Infinite distance 65 | dX = np.sqrt(dT/lamb) # distance increment 66 | nX = int(Xmax/dX) # number of distance elements 67 | 68 | ## Discretisation of variables and initialisation 69 | if cRb == 0: # In case only O present in solution 70 | CR = np.zeros([nT,nX]) 71 | CO = np.ones([nT,nX]) 72 | else: 73 | CR = np.ones([nT,nX]) 74 | CO = np.ones([nT,nX])*cOb/cRb 75 | 76 | 77 | X = np.linspace(0,Xmax,nX) # Discretisation of distance 78 | eps = (E-E0)*n*FRT # adimensional potential waveform 79 | delta = np.sqrt(DR*t[-1]) # cm, diffusion layer thickness 80 | K0 = ks*delta/DR # Normalised standard rate constant 81 | 82 | Cb = np.ones(nX-1) # Cbefore 83 | Cp = -2*np.ones(nX) # Cpresent 84 | Ca = np.ones(nX-1) # Cafter 85 | R = diags([Cb,Cp,Ca], [-1,0,1]).toarray()/(dX**2) 86 | R[0,:] = np.zeros(nX) 87 | R[0,0] = 1 # Initial condition 88 | O = DOR*diags([Cb,Cp,Ca], [-1,0,1]).toarray()/(dX**2) 89 | O[0,:] = np.zeros(nX) # Initial condition 90 | O[0,0] = 1 91 | print(O[0,0]) 92 | 93 | def RK4(y, A): 94 | k1 = fun(y, A) 95 | k2 = fun(y+dT*k1/2, A) 96 | k3 = fun(y+dT*k2/2, A) 97 | k4 = fun(y+dT*k3, A) 98 | return y + (dT/6)*(k1 + 2*k2 + 2*k3 + k4) 99 | 100 | def fun(y, A): 101 | return np.dot(A,y) 102 | 103 | #%% Simulation 104 | for k in range(1,nT): 105 | #print(nT-k) 106 | # Boundary condition, Butler-Volmer: 107 | CR1kb = CR[k-1,1] 108 | CO1kb = CO[k-1,1] 109 | 110 | CR[k,0] = (CR1kb + dX*K0*np.exp(-alpha*eps[k])*(CO1kb + CR1kb/DOR))/( 111 | 1 + dX*K0*(np.exp((1-alpha)*eps[k]) + np.exp(-alpha*eps[k])/DOR)) 112 | CO[k,0] = CO1kb + (CR1kb - CR[k,0])/DOR 113 | 114 | CR[k,1:-1] = RK4(CR[k-1,:], R)[1:-1] 115 | CO[k,1:-1] = RK4(CO[k-1,:], O)[1:-1] 116 | 117 | # Denormalising: 118 | if cRb: 119 | I = -CR[:,2] + 4*CR[:,1] - 3*CR[:,0] 120 | D = DR 121 | c = cRb 122 | else: # In case only O present in solution 123 | I = CO[:,2] - 4*CO[:,1] + 3*CO[:,0] 124 | D = DO 125 | c = cOb 126 | i = n*F*Ageo*D*c*I/(2*dX*delta) 127 | 128 | cR = CR*cRb 129 | cO = CO*cOb 130 | x = X*delta 131 | end = time.time() 132 | print(end-start) 133 | 134 | #%% Plot 135 | p.plot(E, i*1e6, "$E$ / V", "$i$ / $\mu$A") 136 | 137 | -------------------------------------------------------------------------------- /waveforms.py: -------------------------------------------------------------------------------- 1 | #### Function that creates a potential sweep waveform 2 | ''' 3 | Copyright (C) 2020 Oliver Rodriguez 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU General Public License for more details. 12 | You should have received a copy of the GNU General Public License 13 | along with this program. If not, see . 14 | ''' 15 | #### @author oliverrdz 16 | #### https://oliverrdz.xyz 17 | 18 | import numpy as np 19 | 20 | def sweep(Eini = -0.5, Efin = 0.5, sr = 1, dE = 0.01, ns = 2, tini = 0): 21 | """ 22 | 23 | Returns t and E for a sweep potential waveform. 24 | All the parameters are given a default value. 25 | 26 | Parameters 27 | ---------- 28 | Eini: initial potential in V (-0.5 V) 29 | Efin: final potential in V (0.5 V) 30 | sr: scan rate in V/s (1 V/s) 31 | dE: potential increments in V (0.01 V) 32 | ns: number of sweeps (2) 33 | tini: initial time for the sweep (0 s) 34 | 35 | Returns 36 | ------- 37 | t: time array in s 38 | E: potential array in E 39 | 40 | Examples 41 | -------- 42 | >>> import waveforms as wf 43 | >>> t, E = wf.sweep(Eini, Efin, sr, dE, ns) 44 | 45 | Returns t and E calculated with the parameters given 46 | 47 | """ 48 | Ewin = abs(Efin-Eini) # V, potential window of one sweep 49 | tsw = Ewin/sr # s, total time for one sweep 50 | nt = int(Ewin/dE) # number of time and potential elements 51 | 52 | E = np.array([]) # potential array 53 | t = np.linspace(tini,tini + tsw*ns,nt*ns) # time array, it can be created outside the loop 54 | 55 | # for each sweep, test if the sweep number is odd or even and construct the respective sweep 56 | for n in range(1,ns+1): 57 | if (n%2 == 1): 58 | E = np.append(E, np.linspace(Eini, Efin, nt)) # odd 59 | else: 60 | E = np.append(E, np.linspace(Efin, Eini, nt)) # even 61 | 62 | return t, E 63 | 64 | 65 | 66 | def stepE(Estep = 0.5, tini = 0, ttot = 1, dt = 0.01): 67 | """ 68 | 69 | Returns t and E for a step potential waveform. 70 | All the parameters are given a default value. 71 | 72 | Parameters 73 | ---------- 74 | Estep: step potential in V (0.5 V) 75 | tini: initial time for the sweep (0 s) 76 | ttot: total time of the step (1 s) 77 | dt: step time (0.01 s) 78 | 79 | Returns 80 | ------- 81 | t: time array in s 82 | E: potential array in E 83 | 84 | Examples 85 | -------- 86 | >>> import waveforms as wf 87 | >>> t, E = wf.stepE(Estep, tini, ttot, dt) 88 | 89 | Returns t and E calculated with the parameters given 90 | 91 | """ 92 | nt = int(ttot/dt) # number of time elements 93 | tfin = tini + ttot # final time of the step from tini 94 | 95 | E = np.ones([nt])*Estep 96 | t = np.linspace(tini, tfin, nt) 97 | 98 | return t, E 99 | 100 | def stepI(Istep = 1e-6, tini = 0, ttot = 1, dt = 0.01): 101 | """ 102 | 103 | Returns t and E for a step potential waveform. 104 | All the parameters are given a default value. 105 | 106 | Parameters 107 | ---------- 108 | Istep: step current in A (1e-6 A) 109 | tini: initial time for the sweep (0 s) 110 | ttot: total time of the step (1 s) 111 | dt: step time (0.01 s) 112 | 113 | Returns 114 | ------- 115 | t: time array in s 116 | i: current array in A 117 | 118 | Examples 119 | -------- 120 | >>> import waveforms as wf 121 | >>> t, i = wf.stepI(Istep, tini, ttot, dt) 122 | 123 | Returns t and i calculated with the parameters given 124 | 125 | """ 126 | nt = int(ttot/dt) # number of time elements 127 | tfin = tini + ttot # final time of the step from tini 128 | 129 | i = np.ones([nt])*Istep 130 | t = np.linspace(tini, tfin, nt) 131 | 132 | return t, i 133 | -------------------------------------------------------------------------------- /BI_banded-E_RandCirc.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (C) 2020 Oliver Rodriguez 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | You should have received a copy of the GNU General Public License 12 | along with this program. If not, see . 13 | 14 | 15 | Created on Wed Jul 22 10:07:18 2020 16 | * R - e- -> O 17 | * Diffusion with Randless circuit 18 | * Butler Volmer 19 | * Backwards implicit with banded matrix 20 | 21 | Simulation time: 2 s, with: 22 | * dE = 0.0001 (# time elements: 20K) 23 | * dX = 2e-3 (# distance elements: 3K) 24 | 25 | @author: oliverrdz 26 | https://oliverrdz.xyz 27 | ''' 28 | 29 | import numpy as np 30 | from scipy.linalg import solve_banded 31 | import plots as p 32 | import waveforms as wf 33 | import time 34 | 35 | start = time.time() 36 | 37 | ## Electrochemistry constants 38 | F = 96485 # C/mol, Faraday constant 39 | R = 8.315 # J/mol K, Gas constant 40 | T = 298 # K, Temperature 41 | FRT = F/(R*T) 42 | 43 | #%% Parameters 44 | 45 | n = 1 # number of electrons 46 | cB = 1e-6 # mol/cm3, bulk concentration of R 47 | D = 1e-5 # cm2/s, diffusion coefficient of R 48 | Ageo = 1 # cm2, geometrical area 49 | r = np.sqrt(Ageo/np.pi) # cm, radius of electrode 50 | ks = 1e-3 # cm/s, standard rate constant 51 | alpha = 0.5 # transfer coefficient 52 | 53 | Rf = 5 # Roughness factor 54 | C = 20e-6 # F/cm2, specific capacitance 55 | x = 0.1 # cm, Luggin electrode distance 56 | kapa = 0.0632 # Ohm-1 cm-1, conductivity for 0.5 M NaCl 57 | Cdl = Ageo*Rf*C # F, double layer capacitance 58 | Ru = x/(kapa*Ageo) # Ohms, solution resistance 59 | 60 | # Potential waveform 61 | E0 = 0 # V, standard potential 62 | Eini = -0.5 # V, initial potential 63 | Efin = 0.5 # V, final potential vertex 64 | sr = 1 # V/s, scan rate 65 | ns = 2 # number of sweeps 66 | dE = 0.0001 # V, potential increment. This value has to be small for BI to approximate the circuit properly 67 | 68 | t, E = wf.sweep(Eini=Eini, Efin=Efin, dE=dE, sr=sr, ns=ns) # Creates waveform 69 | 70 | #%% Simulation parameters 71 | delta = np.sqrt(D*t[-1]) # cm, diffusion layer thickness 72 | maxT = 1 # Time normalised by total time 73 | dt = t[1] # t[1] - t[0]; t[0] = 0 74 | dT = dt/t[-1] # normalised time increment 75 | nT = np.size(t) # number of time elements 76 | 77 | maxX = 6*np.sqrt(maxT) # Normalised maximum distance 78 | dX = 2e-3 # normalised distance increment 79 | nX = int(maxX/dX) # number of distance elements 80 | X = np.linspace(0,maxX,nX) # normalised distance array 81 | 82 | K0 = ks*delta/D # Normalised standard rate constant 83 | lamb = dT/dX**2 84 | 85 | # Thomas coefficients 86 | a = -lamb 87 | b = 1 + 2*lamb 88 | g = -lamb 89 | 90 | C = np.ones([nT,nX]) # Initial condition for C 91 | V = np.zeros(nT+1) 92 | iF = np.zeros(nT) 93 | 94 | # Constructing ab to use in solve_banded: 95 | ab = np.zeros([3,nX]) 96 | ab[0,2:] = g 97 | ab[1,:] = b 98 | ab[2,:-2] = a 99 | ab[1,0] = 1 100 | ab[1,-1] = 1 101 | 102 | # Initial condition for V 103 | V[0] = E[0] 104 | 105 | #%% Simulation 106 | for k in range(0,nT-1): 107 | eps = FRT*(V[k] - E0) 108 | 109 | # Butler-Volmer: 110 | b0 = -(1 +dX*K0*(np.exp((1-alpha)*eps) + np.exp(-alpha*eps))) 111 | g0 = 1 112 | 113 | # Updating ab with the new values 114 | ab[0,1] = g0 115 | ab[1,0] = b0 116 | 117 | # Boundary conditions: 118 | C[k,0] = -dX*K0*np.exp(-alpha*eps) 119 | C[k,-1] = 1 120 | 121 | C[k+1,:] = solve_banded((1,1), ab, C[k,:]) 122 | 123 | # Obtaining faradaic current and solving voltage drop 124 | iF[k] = n*F*Ageo*D*cB*(-C[k+1,2] + 4*C[k+1,1] - 3*C[k+1,0])/(2*dX*delta) 125 | V[k+1] = (V[k] + (t[1]/Cdl)*(E[k]/Ru -iF[k]))/(1 + t[1]/(Cdl*Ru)) 126 | 127 | i = (E-V[:-1])/Ru 128 | 129 | # Denormalising: 130 | cR = C*cB 131 | cO = cB - cR 132 | x = X*delta 133 | end = time.time() 134 | print(end-start) 135 | 136 | #%% Plot 137 | p.plot(E, i, "$E$ / V", "$i$ / A") 138 | p.plot2(x, cR[-1,:]*1e6, x, cO[-1,:]*1e6, "[R]", "[O]", "x / cm", "c($t_{end}$,$x$=0) / mM") 139 | -------------------------------------------------------------------------------- /softpotato/simulation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import numpy as np 4 | from scipy.linalg import solve_banded 5 | 6 | ## Electrochemistry constants 7 | F = 96485 # C/mol, Faraday constant 8 | R = 8.315 # J/mol K, Gas constant 9 | T = 298 # K, Temperature 10 | FRT = F/(R*T) 11 | 12 | class FD: 13 | 14 | def __init__(self, wf, n=1, Ageo=1, cOb=1e-6, cRb=1e-6, DO=1e-5, DR=1e-5, 15 | E0=0, ks=1e5, alpha=0.5): 16 | E = wf.E 17 | t = wf.t 18 | 19 | DOR = DO/DR 20 | 21 | nT = np.size(t) 22 | dT = 1/nT 23 | lamb = 0.45 24 | #%% Simulation parameters 25 | nT = np.size(t) # number of time elements 26 | dT = 1/nT # adimensional step time 27 | lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 28 | Xmax = 6*np.sqrt(nT*lamb) # Infinite distance 29 | dX = np.sqrt(dT/lamb) # distance increment 30 | nX = int(Xmax/dX) # number of distance elements 31 | 32 | ## Discretisation of variables and initialisation 33 | CR = np.ones([nT,nX]) # Initial condition for R 34 | CO = np.ones([nT,nX])*cOb/cRb 35 | X = np.linspace(0,Xmax,nX) # Discretisation of distance 36 | eps = (E-E0)*n*FRT # adimensional potential waveform 37 | delta = np.sqrt(DR*t[-1]) # cm, diffusion layer thickness 38 | K0 = ks*delta/DR # Normalised standard rate constant 39 | 40 | #%% Simulation 41 | for k in range(1,nT): 42 | # Boundary condition, Butler-Volmer: 43 | #CR[k,0] = (CR[k-1,1] + dX*K0*np.exp(-alpha*eps[k]))/( 44 | # 1+dX*K0*(np.exp((1-alpha)*eps[k])+np.exp(-alpha*eps[k]))) 45 | CR1kb = CR[k-1,1] 46 | CO1kb = CO[k-1,1] 47 | CR[k,0] = (CR1kb + dX*K0*np.exp(-alpha*eps[k])*(CO1kb + CR1kb/DOR))/( 48 | 1 + dX*K0*(np.exp((1-alpha)*eps[k]) + np.exp(-alpha*eps[k])/DOR)) 49 | CO[k,0] = CO1kb + (CR1kb - CR[k,0])/DOR 50 | 51 | # Solving finite differences: 52 | for j in range(1,nX-1): 53 | #CR[k,j] = CR[k-1,j] + lamb*(CR[k-1,j+1] - 2*CR[k-1,j] + CR[k-1,j-1]) 54 | CR[k,j] = CR[k-1,j] + lamb*(CR[k-1,j+1] - 2*CR[k-1,j] + CR[k-1,j-1]) 55 | CO[k,j] = CO[k-1,j] + DOR*lamb*(CO[k-1,j+1] - 2*CO[k-1,j] + CO[k-1,j-1]) 56 | 57 | # Denormalising: 58 | i = n*F*Ageo*DR*cRb*(-CR[:,2] + 4*CR[:,1] - 3*CR[:,0])/(2*dX*delta) 59 | cR = CR*cRb 60 | cO = cRb - cR 61 | x = X*delta 62 | 63 | self.E = E 64 | self.t = t 65 | self.i = i 66 | self.cR = cR 67 | self.cO = cO 68 | self.x = x 69 | 70 | 71 | class BI: 72 | 73 | def __init__(self, wf, n=1, Ageo=1, cB=1e-6, D=1e-5, E0=0, ks=1e8, alpha=0.5): 74 | E = wf.E 75 | t = wf.t 76 | 77 | #%% Simulation parameters 78 | delta = np.sqrt(D*t[-1]) # cm, diffusion layer thickness 79 | maxT = 1 # Time normalised by total time 80 | dt = t[1] # t[1] - t[0]; t[0] = 0 81 | dT = dt/t[-1] # normalised time increment 82 | nT = np.size(t) # number of time elements 83 | 84 | maxX = 6*np.sqrt(maxT) # Normalised maximum distance 85 | dX = 2e-3 # normalised distance increment 86 | nX = int(maxX/dX) # number of distance elements 87 | X = np.linspace(0,maxX,nX) # normalised distance array 88 | 89 | K0 = ks*delta/D # Normalised standard rate constant 90 | lamb = dT/dX**2 91 | 92 | # Thomas coefficients 93 | a = -lamb 94 | b = 1 + 2*lamb 95 | g = -lamb 96 | 97 | C = np.ones([nT,nX]) # Initial condition for C 98 | V = np.zeros(nT+1) 99 | i = np.zeros(nT) 100 | 101 | # Constructing ab to use in solve_banded: 102 | ab = np.zeros([3,nX]) 103 | ab[0,2:] = g 104 | ab[1,:] = b 105 | ab[2,:-2] = a 106 | ab[1,0] = 1 107 | ab[1,-1] = 1 108 | 109 | # Initial condition for V 110 | V[0] = E[0] 111 | 112 | #%% Simulation 113 | for k in range(0,nT-1): 114 | eps = FRT*(E[k] - E0) 115 | 116 | # Butler-Volmer: 117 | b0 = -(1 +dX*K0*(np.exp((1-alpha)*eps) + np.exp(-alpha*eps))) 118 | g0 = 1 119 | 120 | # Updating ab with the new values 121 | ab[0,1] = g0 122 | ab[1,0] = b0 123 | 124 | # Boundary conditions: 125 | C[k,0] = -dX*K0*np.exp(-alpha*eps) 126 | C[k,-1] = 1 127 | 128 | C[k+1,:] = solve_banded((1,1), ab, C[k,:]) 129 | 130 | # Obtaining faradaic current and solving voltage drop 131 | i[k] = n*F*Ageo*D*cB*(-C[k+1,2] + 4*C[k+1,1] - 3*C[k+1,0])/(2*dX*delta) 132 | 133 | # Denormalising: 134 | cR = C*cB 135 | cO = cB - cR 136 | x = X*delta 137 | 138 | self.t = t 139 | self.E = E 140 | self.i = i 141 | self.cR = cR 142 | self.cO = cO 143 | self.x = x 144 | 145 | -------------------------------------------------------------------------------- /cottrell/solver.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from .mesh1d import Mesh1D 3 | try: 4 | from scipy.integrate import solve_ivp 5 | except ImportError: 6 | solve_ivp = None 7 | 8 | class PlanarDiffusionSolver: 9 | def __init__(self, D_cm2_s, C_bulk_mM, t_final_s, 10 | dt_s=None, NX=101, lambda_value=0.4, 11 | n_elec=1, A_cm2=1.0, grid_type="uniform", 12 | stretch_factor=1.05, method="explicit", 13 | geometry="planar", r0_cm=0.01, 14 | L_thinlayer_cm=1e-3, omega_rpm=1000.0, 15 | nu_cm2_s=0.01): 16 | 17 | self.geometry = geometry.lower().replace("-","_") 18 | self.C_bulk_mM = C_bulk_mM 19 | self.t_final_s = t_final_s 20 | self.dt_s = dt_s 21 | self.NX = NX 22 | self.lambda_value = lambda_value 23 | self.n = n_elec 24 | self.A_cm2 = A_cm2 25 | self.grid_type = grid_type 26 | self.stretch_factor = stretch_factor 27 | self.F = 96485.0 28 | self.r0_m = r0_cm*1e-2 29 | self.L_thinlayer_cm = L_thinlayer_cm 30 | self.omega_rpm = omega_rpm 31 | self.nu_cm2_s = nu_cm2_s 32 | self.method = method.lower() 33 | 34 | # Diffusion coefficient to SI 35 | self.D = D_cm2_s*1e-4 36 | # Characteristic diffusion length 37 | self.delta_m = np.sqrt(self.D*t_final_s) 38 | 39 | # Domain length by geometry 40 | if self.geometry in ("planar","spherical","cylindrical","microband"): 41 | L_m = 6*self.delta_m 42 | elif self.geometry=="thin_layer": 43 | L_m = self.L_thinlayer_cm*1e-2 44 | elif self.geometry=="rde": 45 | L_m = self._compute_rde_delta() 46 | elif self.geometry=="rce": 47 | L_m = self._compute_rce_delta() 48 | else: 49 | raise ValueError("bad geometry") 50 | 51 | # Inner coordinate (planar at x=0, radial at r=r0) 52 | x0_m = self.r0_m if self.geometry in ("spherical","cylindrical","microband") else 0.0 53 | 54 | # Mesh 55 | self.mesh = Mesh1D(L_m, NX, x0_m, grid_type, stretch_factor, self.geometry) 56 | 57 | # Allocate arrays, time grid 58 | self._allocate_arrays() 59 | 60 | def _compute_rde_delta(self): 61 | """RDE effective diffusion layer thickness (Levich-type).""" 62 | nu = self.nu_cm2_s*1e-4 # cm^2/s -> m^2/s 63 | omega = 2*np.pi*self.omega_rpm/60.0 64 | return 1.61*(self.D**(1.0/3.0))*(nu**(1.0/6.0))*(omega**-0.5) 65 | 66 | def _compute_rce_delta(self): 67 | """RCE effective diffusion layer thickness (similar scaling to RDE).""" 68 | nu = self.nu_cm2_s*1e-4 69 | omega = 2*np.pi*self.omega_rpm/60.0 70 | # slightly different prefactor; here we just use 1.47 as an example 71 | return 1.47*(self.D**(1.0/3.0))*(nu**(1.0/6.0))*(omega**-0.5) 72 | 73 | def _allocate_arrays(self): 74 | self.c = np.ones(self.NX)*self.C_bulk_mM 75 | self.i_t = [] 76 | self.t_s = [] 77 | 78 | if self.dt_s is None: 79 | dx = self.mesh.dx_m 80 | self.dt_s = self.lambda_value*dx*dx/self.D 81 | self.NT = int(self.t_final_s/self.dt_s)+1 82 | 83 | def _compute_current(self): 84 | dc_dx = (self.c[1]-self.c[0])/self.mesh.dx_m 85 | # Use planar area unless spherical; A_cm2 is user-defined for all non-spherical 86 | if self.geometry == "spherical": 87 | A_m2 = 4*np.pi*self.r0_m**2 88 | else: 89 | A_m2 = self.A_cm2*1e-4 90 | return -self.n*self.F*A_m2*self.D*dc_dx 91 | 92 | def solve(self): 93 | for k in range(self.NT): 94 | self.t_s.append(k*self.dt_s) 95 | self.i_t.append(self._compute_current()) 96 | self._step() 97 | self.t_s = np.array(self.t_s) 98 | self.i_t = np.array(self.i_t) 99 | 100 | def _step(self): 101 | # explicit diffusion update with geometry-dependent Laplacian 102 | c = self.c 103 | D = self.D 104 | dt = self.dt_s 105 | dx = self.mesh.dx_m 106 | x = self.mesh.x_m 107 | c_new = c.copy() 108 | 109 | geom = self.geometry 110 | 111 | for i in range(1, self.NX-1): 112 | if geom in ("planar","thin_layer","rde","rce"): 113 | # standard 1D planar diffusion 114 | d2 = (c[i+1]-2*c[i]+c[i-1])/(dx*dx) 115 | c_new[i] = c[i] + D*dt*d2 116 | elif geom == "spherical": 117 | r = x[i] 118 | dcdr = (c[i+1]-c[i-1])/(2*dx) 119 | d2cdr2 = (c[i+1]-2*c[i]+c[i-1])/(dx*dx) 120 | rhs = d2cdr2 + 2.0*dcdr/r 121 | c_new[i] = c[i] + D*dt*rhs 122 | elif geom in ("cylindrical","microband"): 123 | r = x[i] 124 | dcdr = (c[i+1]-c[i-1])/(2*dx) 125 | d2cdr2 = (c[i+1]-2*c[i]+c[i-1])/(dx*dx) 126 | rhs = d2cdr2 + 1.0*dcdr/r 127 | c_new[i] = c[i] + D*dt*rhs 128 | else: 129 | # fallback: planar 130 | d2 = (c[i+1]-2*c[i]+c[i-1])/(dx*dx) 131 | c_new[i] = c[i] + D*dt*d2 132 | 133 | # Inner boundary: electrode surface (Dirichlet c=0) 134 | c_new[0] = 0.0 135 | 136 | # Outer boundary: bulk concentration for all current geometries 137 | c_new[-1] = self.C_bulk_mM 138 | 139 | self.c = c_new 140 | -------------------------------------------------------------------------------- /RK4_EC_OOP.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.sparse import diags 3 | 4 | ## Electrochemistry constants 5 | F = 96485 # C/mol, Faraday constant 6 | R = 8.315 # J/mol K, Gas constant 7 | T = 298 # K, Temperature 8 | FRT = F/(R*T) 9 | 10 | class E: 11 | ''' 12 | Defines an E species 13 | ''' 14 | def __init__(self, n=1, DO=1e-5, DR=1e-5, cOb=0, cRb=1e-6, E0=0, ks=1e8, 15 | alpha=0.5): 16 | self.n = n 17 | self.DO = DO 18 | self.DR = DR 19 | self.DOR = DO/DR 20 | self.cOb = cOb 21 | self.cRb = cRb 22 | self.E0 = E0 23 | self.ks = ks 24 | self.alpha = alpha 25 | 26 | 27 | class C: 28 | ''' 29 | Defines a C species 30 | ''' 31 | def __init__(self, DP=1e-5, cPb=0, kc=1e-2): 32 | self.DP = DP 33 | self.cPb = cPb 34 | self.kc = kc 35 | print(self.kc) 36 | 37 | 38 | class TGrid: 39 | ''' 40 | Defines the grid in time 41 | ''' 42 | def __init__(self, twf, Ewf): 43 | self.t = twf 44 | self.E = Ewf 45 | self.nT = np.size(self.t) # number of time elements 46 | self.dT = 1/self.nT # adimensional step time 47 | 48 | 49 | class XGrid: 50 | ''' 51 | Defines the grid in space 52 | ''' 53 | def __init__(self, species, tgrid, Ageo=1): 54 | self.lamb = 0.45 # For the algorithm to be stable, lamb = dT/dX^2 < 0.5 55 | self.Xmax = 6*np.sqrt(tgrid.nT*self.lamb) # Infinite distance 56 | self.dX = np.sqrt(tgrid.dT/self.lamb) # distance increment 57 | self.nX = int(self.Xmax/self.dX) # number of distance elements 58 | self.X = np.linspace(0, self.Xmax, self.nX) # Discretisation of distance 59 | self.Ageo = Ageo 60 | 61 | for x in species: 62 | if isinstance(x, E): 63 | ## Discretisation of variables and initialisation 64 | if x.cRb == 0: # In case only O present in solution 65 | x.CR = np.zeros([tgrid.nT, self.nX]) 66 | x.CO = np.ones([tgrid.nT, self.nX]) 67 | else: 68 | x.CR = np.ones([tgrid.nT, self.nX]) 69 | 70 | x.eps = (tgrid.E-x.E0)*x.n*FRT # adimensional potential waveform 71 | x.delta = np.sqrt(x.DR*tgrid.t[-1]) # cm, diffusion layer thickness 72 | x.Ke = x.ks*x.delta/x.DR # Normalised standard rate constant 73 | x.CO = np.ones([tgrid.nT, self.nX])*x.cOb/x.cRb 74 | # Construct matrix: 75 | Cb = np.ones(self.nX-1) # Cbefore 76 | Cp = -2*np.ones(self.nX) # Cpresent 77 | Ca = np.ones(self.nX-1) # Cafter 78 | x.A = diags([Cb,Cp,Ca], [-1,0,1]).toarray()/(self.dX**2) 79 | x.A[0,:] = np.zeros(self.nX) 80 | x.A[0,0] = 1 # Initial condition 81 | else: 82 | x.CP = np.zeros([tgrid.nT, self.nX]) 83 | 84 | 85 | class Simulate: 86 | ''' 87 | ''' 88 | def __init__(self, species, mech, tgrid, xgrid): 89 | self.species = species 90 | self.mech = mech 91 | self.tgrid = tgrid 92 | self.xgrid = xgrid 93 | 94 | self.join(species) 95 | 96 | def sim(self): 97 | nE = self.nE[0] 98 | nC = self.nC[0] 99 | sE = self.species[nE] 100 | sC = self.species[nC] 101 | for k in range(1, tgrid.nT): 102 | #print(tgrid.nT-k) 103 | # Boundary condition, Butler-Volmer: 104 | CR1kb = sE.CR[k-1,1] 105 | CO1kb = sE.CO[k-1,1] 106 | sE.CR[k,0] = (CR1kb + xgrid.dX*sE.Ke*np.exp(-sE.alpha*sE.eps[k] 107 | )*(CO1kb + CR1kb/sE.DOR))/(1 + xgrid.dX*sE.Ke*( 108 | np.exp((1-sE.alpha)*sE.eps[k])+np.exp( 109 | -sE.alpha*sE.eps[k])/sE.DOR)) 110 | sE.CO[k,0] = CO1kb + (CR1kb - sE.CR[k,0])/sE.DOR 111 | # Runge-Kutta 4: 112 | sE.CR[k,1:-1] = self.RK4(sE.CR[k-1,:], 'E', sE)[1:-1] 113 | if self.mech == 'E': 114 | sE.CO[k,1:-1] = self.RK4(sE.CO[k-1,:], 'E', sE)[1:-1] 115 | elif self.mech == 'EC': 116 | sE.CO[k,1:-1] = self.RK4(sE.CO[k-1,:], 'EC', sE, sC)[1:-1] 117 | #sC.CP[k,1:-1] = self.RK4(sC.CP[k-1,:], 'EC', sC, 118 | 119 | 120 | for s in self.species: 121 | if isinstance(s, E): 122 | # Denormalising: 123 | if s.cRb: 124 | I = -s.CR[:,2] + 4*s.CR[:,1] - 3*s.CR[:,0] 125 | D = s.DR 126 | c = s.cRb 127 | else: # In case only O present in solution 128 | I = s.CO[:,2] - 4*s.CO[:,1] + 3*s.CO[:,0] 129 | D = s.DO 130 | c = s.cOb 131 | self.i = s.n*F*self.xgrid.Ageo*D*c*I/(2*self.xgrid.dX*s.delta) 132 | 133 | s.cR = s.CR*s.cRb 134 | s.cO = s.CO*s.cOb 135 | self.x = self.xgrid.X*s.delta 136 | 137 | def join(self, species): 138 | ns = len(species) 139 | self.nE = [] 140 | self.nC = [] 141 | for s in range(ns): 142 | if isinstance(species[s], E): 143 | self.nE.append(s) 144 | elif isinstance(species[s], C): 145 | self.nC.append(s) 146 | 147 | if self.mech == 'EC': 148 | species[self.nC[0]].Kc = species[self.nC[0]].kc* \ 149 | species[self.nE[0]].delta/ \ 150 | species[self.nE[0]].DR 151 | 152 | def fun(self, y, mech, species, params): 153 | rate = 0 154 | if mech == 'EC': 155 | rate = - self.tgrid.dT*params.Kc*y 156 | return np.dot(species.A, y) + rate 157 | 158 | def RK4(self, y, mech, species, params=0): 159 | dT = self.tgrid.dT 160 | k1 = self.fun(y, mech, species, params) 161 | k2 = self.fun(y+dT*k1/2, mech, species, params) 162 | k3 = self.fun(y+dT*k2/2, mech, species, params) 163 | k4 = self.fun(y+dT*k3, mech, species, params) 164 | return y + (dT/6)*(k1 + 2*k2 + 2*k3 + k4) 165 | 166 | 167 | 168 | 169 | 170 | if __name__ == '__main__': 171 | import waveforms as wf 172 | import plots as p 173 | 174 | e = E(ks=1e8) 175 | c = C(kc=kc[y]) 176 | twf, Ewf = wf.sweep(sr=0.01) 177 | e = E() 178 | c = C(kc=kc) 179 | tgrid = TGrid(twf, Ewf) 180 | xgrid = XGrid([e,c], tgrid) 181 | sim = Simulate([e,c], 'EC', tgrid, xgrid) 182 | sim.sim() 183 | p.plot(Ewf, sim.i, xlab='$E$ / V', ylab='$i$ / A') 184 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------