pySIMSalabim 1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. pySIMsalabim/__init__.py +21 -0
  2. pySIMsalabim/aux_funcs/SCLC_funcs.py +561 -0
  3. pySIMsalabim/aux_funcs/__init__.py +0 -0
  4. pySIMsalabim/aux_funcs/addons.py +55 -0
  5. pySIMsalabim/experiments/CV.py +918 -0
  6. pySIMsalabim/experiments/EQE.py +461 -0
  7. pySIMsalabim/experiments/JV_steady_state.py +259 -0
  8. pySIMsalabim/experiments/__init__.py +0 -0
  9. pySIMsalabim/experiments/hysteresis.py +753 -0
  10. pySIMsalabim/experiments/impedance.py +848 -0
  11. pySIMsalabim/experiments/imps.py +630 -0
  12. pySIMsalabim/install/__init__.py +20 -0
  13. pySIMsalabim/install/compile_simsalabim.py +76 -0
  14. pySIMsalabim/install/get_SIMsalabim.py +505 -0
  15. pySIMsalabim/install/get_gnu_parallel.py +107 -0
  16. pySIMsalabim/plots/__init__.py +0 -0
  17. pySIMsalabim/plots/band_diagram.py +209 -0
  18. pySIMsalabim/plots/plot_def.py +19 -0
  19. pySIMsalabim/plots/plot_functions.py +240 -0
  20. pySIMsalabim/tests/__init__.py +0 -0
  21. pySIMsalabim/tests/test_CV.py +91 -0
  22. pySIMsalabim/tests/test_EQE.py +97 -0
  23. pySIMsalabim/tests/test_IMPS.py +92 -0
  24. pySIMsalabim/tests/test_JV.py +88 -0
  25. pySIMsalabim/tests/test_hyst.py +92 -0
  26. pySIMsalabim/tests/test_impedance.py +89 -0
  27. pySIMsalabim/utils/__init__.py +25 -0
  28. pySIMsalabim/utils/clean_up.py +96 -0
  29. pySIMsalabim/utils/device_parameters.py +720 -0
  30. pySIMsalabim/utils/general.py +521 -0
  31. pySIMsalabim/utils/parallel_sim.py +654 -0
  32. pySIMsalabim/utils/utils.py +129 -0
  33. pySIMsalabim-1.dist-info/LICENSE +674 -0
  34. pySIMsalabim-1.dist-info/METADATA +159 -0
  35. pySIMsalabim-1.dist-info/RECORD +37 -0
  36. pySIMsalabim-1.dist-info/WHEEL +5 -0
  37. pySIMsalabim-1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,918 @@
1
+ """Perform capacitance simulations"""
2
+ ######### Package Imports #########################################################################
3
+
4
+ import os, sys
5
+ import numpy as np
6
+ import pandas as pd
7
+ import matplotlib.pyplot as plt
8
+ import math
9
+ import scipy.integrate
10
+ # import pySIMsalabim
11
+ ## Import pySIMsalabim, if not successful, add the parent directory to the system path
12
+ try :
13
+ import pySIMsalabim as sim
14
+ except ImportError:
15
+ # Add the parent directory to the system path
16
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
17
+ import pySIMsalabim as sim
18
+ from pySIMsalabim.utils import general as utils_gen
19
+ from pySIMsalabim.plots import plot_functions as utils_plot
20
+ from pySIMsalabim.utils.utils import *
21
+ from pySIMsalabim.utils.device_parameters import *
22
+
23
+ ######### Function Definitions ####################################################################
24
+
25
+ def create_tVG_CV(V_0, V_max, del_V, V_step, G_frac, tVG_name, session_path, freq, ini_timeFactor, timeFactor):
26
+ """Create a tVG file for capacitance experiment.
27
+
28
+ Parameters
29
+ ----------
30
+ V_0 : float
31
+ Initial voltage
32
+ V_max : float
33
+ Maximum voltage
34
+ del_V : float
35
+ Voltage step that is applied directly after t=0
36
+ V_step : float
37
+ Voltage difference, determines at which voltages the capacitance is determined
38
+ G_frac : float
39
+ Fractional light intensity
40
+ tVG_name : string
41
+ Name of the tVG file
42
+ session_path : string
43
+ Path of the simulation folder for this session
44
+ freq : float
45
+ Frequency at which the capacitance-voltage measurement is performed
46
+ ini_timeFactor : float
47
+ Constant defining the size of the initial timestep
48
+ timeFactor : float
49
+ Exponential increase of the timestep, to reduce the amount of timepoints necessary. Use values close to 1.
50
+
51
+ Returns
52
+ -------
53
+ string
54
+ A message to indicate the result of the process
55
+ """
56
+
57
+ # Starting line of the tVG file: header + datapoints at time=0. Set the correct header
58
+ tVG_lines = 't Vext G_frac\n'
59
+
60
+ # Loop until V reaches V_max, in other words go from Vmin to Vmax with in V_step steps. Add some extra margin on the Vmax to prevent missing the last voltage point due to numerical accuracy.
61
+ while V_0 <= V_max + V_max*1E-5:
62
+ time = 0
63
+ del_t = ini_timeFactor/freq
64
+ tVG_lines += f'{time:.3e} {V_0:.3e} {G_frac:.3e}\n'
65
+
66
+ # Make the other lines in the tVG file
67
+ while time < 1/freq: #max time: 1/f_min is enough!
68
+ time += del_t
69
+ del_t = del_t * timeFactor
70
+ tVG_lines += f'{time:.3e} {V_0+del_V:.3e} {G_frac:.3e}\n'
71
+
72
+ V_0 += V_step
73
+
74
+ # Write the tVG lines to the tVG file
75
+ with open(os.path.join(session_path,tVG_name), 'w') as file:
76
+ file.write(tVG_lines)
77
+
78
+ # tVG file is created, message a success
79
+ msg = 'Success'
80
+ retval = 0
81
+
82
+ return retval, msg
83
+
84
+ def create_tVG_CV_Rseries(Vint, del_V, G_frac, tVG_name, session_path, freq, ini_timeFactor, timeFactor):
85
+ """Create a tVG file for capacitance experiment.
86
+
87
+ Parameters
88
+ ----------
89
+ V_int : float
90
+ Adjusted internal voltage to correct for series resistance later
91
+ del_V : float
92
+ Voltage step that is applied directly after t=0
93
+ G_frac : float
94
+ Fractional light intensity
95
+ tVG_name : string
96
+ Name of the tVG file
97
+ session_path : string
98
+ Path of the simulation folder for this session
99
+ freq : float
100
+ Frequency at which the capacitance-voltage measurement is performed
101
+ ini_timeFactor : float
102
+ Constant defining the size of the initial timestep
103
+ timeFactor : float
104
+ Exponential increase of the timestep, to reduce the amount of timepoints necessary. Use values close to 1.
105
+
106
+ Returns
107
+ -------
108
+ string
109
+ A message to indicate the result of the process
110
+ """
111
+
112
+ # Starting line of the tVG file: header + datapoints at time=0. Set the correct header
113
+ tVG_lines = 't Vext G_frac\n'
114
+
115
+ # Loop until V reaches V_max, in other words go from Vmin to Vmax with in V_step steps. Add some extra margin on the Vmax to prevent missing the last voltage point due to numerical accuracy.
116
+ for V_0 in Vint:
117
+ time = 0
118
+ del_t = ini_timeFactor/freq
119
+ tVG_lines += f'{time:.3e} {V_0:.3e} {G_frac:.3e}\n'
120
+
121
+ # Make the other lines in the tVG file
122
+ while time < 1/freq:
123
+ time += del_t
124
+ del_t = del_t * timeFactor
125
+ tVG_lines += f'{time:.3e} {V_0+del_V:.3e} {G_frac:.3e}\n'
126
+
127
+ # while V_0 <= V_max + V_max*1E-5:
128
+ # time = 0
129
+ # del_t = ini_timeFactor/freq
130
+ # tVG_lines += f'{time:.3e} {V_0:.3e} {G_frac:.3e}\n'
131
+
132
+ # # Make the other lines in the tVG file
133
+ # while time < 1/freq: #max time: 1/f_min is enough!
134
+ # time += del_t
135
+ # del_t = del_t * timeFactor
136
+ # tVG_lines += f'{time:.3e} {V_0+del_V:.3e} {G_frac:.3e}\n'
137
+
138
+ # V_0 += V_step
139
+
140
+ # Write the tVG lines to the tVG file
141
+ with open(os.path.join(session_path,tVG_name), 'w') as file:
142
+ file.write(tVG_lines)
143
+
144
+ # tVG file is created, message a success
145
+ msg = 'Success'
146
+ retval = 0
147
+
148
+ return retval, msg
149
+
150
+ def create_tVG_SS_CV(V_min, V_max,Vstep, G_frac, tVG_name, session_path):
151
+ """ Creates the tVG file for the steady state simulation with only t 0 and V_0
152
+
153
+ Parameters
154
+ ----------
155
+ V_min : float
156
+ Initial voltage
157
+ V_max : float
158
+ Maximum voltage
159
+ del_V : float
160
+ Voltage step that is applied after t=0
161
+ G_frac : float
162
+ Fractional light intensity
163
+ tVG_name : string
164
+ Name of the tVG file
165
+ session_path : string
166
+ Path of the simulation folder for this session
167
+
168
+ Returns
169
+ -------
170
+ string
171
+ A message to indicate the result of the process
172
+
173
+
174
+ """
175
+
176
+ # Starting line of the tVG file: header + datapoints at time=0. Set the correct header
177
+ tVG_lines = 't Vext G_frac\n' #+ f'{0} {V_0} {G_frac:.3e}\n'
178
+ V_0 =V_min
179
+ while V_0 <= V_max + V_max*1E-5:
180
+ time = 0
181
+ tVG_lines += f'{time:.3e} {V_0:.3e} {G_frac:.3e}\n'
182
+ V_0 += Vstep
183
+
184
+ # Write the tVG lines to the tVG file
185
+ with open(os.path.join(session_path,tVG_name), 'w') as file:
186
+ file.write(tVG_lines)
187
+
188
+ # tVG file is created, message a success
189
+ msg = 'Success'
190
+ retval = 0
191
+
192
+ return retval, msg
193
+
194
+ def calc_capacitance_forOneVoltage(I, errI, time, VStep, freq):
195
+ """Fourier Decomposition formula which computes the capacitance at frequency freq (Hz) and its complex error
196
+ Based on S.E. Laux, IEEE Trans. Electron Dev. 32 (10), 2028 (1985), eq. 5b
197
+ We integrate from 0 to time[imax] at frequency 1/time[imax]
198
+
199
+ Parameters
200
+ ----------
201
+ I : np.array
202
+ Array of currents
203
+ errI : np.array
204
+ Numerical error in calculated currents (output of ZimT)
205
+ time : np.array
206
+ Array with all time positions, from 0 to tmax
207
+ VStep : float
208
+ Voltage step
209
+ imax : integer
210
+ Index of the last timestep/first frequency for which the integrals are calculated
211
+
212
+ Returns
213
+ -------
214
+ float
215
+ Capacitance at frequency f: C(f)
216
+ float
217
+ Numerical error in calculated capacitance
218
+ """
219
+
220
+ imax = len(I)
221
+ Iinf = I[imax-1] # I at infinite time, i.e. the last one we have.
222
+
223
+ #prepare array for integrants:
224
+ int2 = np.empty(imax)
225
+ int4 = np.empty(imax)
226
+
227
+ for i in range(imax):
228
+ cosfac = math.cos(2*math.pi*freq*time[i])
229
+ int2[i] = cosfac*(I[i] - Iinf)
230
+ int4[i] = cosfac*(I[i] + errI[i] - Iinf - errI[imax-1])
231
+
232
+ #Compute the capacitance:
233
+ cap = scipy.integrate.trapezoid(int2, time)/VStep
234
+
235
+ #and again, but now with the error added to the current:
236
+ capErr = scipy.integrate.trapezoid(int4, time)/VStep
237
+
238
+ # error is the difference between cap and capPlusErr:
239
+ errC = abs( cap - capErr )
240
+
241
+ #now return capacitance, its error and the corresponding frequency:
242
+ return cap, errC
243
+
244
+ def calc_capacitance(data, del_V, freq):
245
+ """ Calculate the capacitance over the time range
246
+
247
+ Parameters
248
+ ----------
249
+ data : dataFrame
250
+ Pandas dataFrame containing the time, voltage, current density and numerical error in the current density of the tj_file
251
+ del_V : float
252
+ Voltage step that is applied directly after t=0
253
+ freq : float
254
+ Frequency at which the capacitance-voltage measurement is performed
255
+
256
+ Returns
257
+ -------
258
+ np.array
259
+ Array of the capacitance
260
+ np.array
261
+ Array of the capacitance error
262
+ """
263
+
264
+ idx_time_zero = data.index[data['t'] == 0] # Find all indices where time is equal to 0
265
+ amountOfVoltagePoints = len(idx_time_zero)
266
+
267
+ # Prepare array for capacitance & its error:
268
+ cap = np.empty(amountOfVoltagePoints)
269
+ errC = np.empty(amountOfVoltagePoints)
270
+
271
+ # Get the capacitance for each voltage step by taking the Fourier Transform over the t & I arrays
272
+ for i in range(amountOfVoltagePoints-1):
273
+ start_idx = idx_time_zero[i]
274
+ end_idx = idx_time_zero[i+1]-1
275
+
276
+ Jext_subarray = np.array( data.loc[start_idx:end_idx, 'Jext'] )
277
+ errJ_subarray = np.array( data.loc[start_idx:end_idx, 'errJ'] )
278
+ time_subarray = np.array( data.loc[start_idx:end_idx, 't'] )
279
+
280
+ cap[i], errC[i] = calc_capacitance_forOneVoltage(Jext_subarray, errJ_subarray, time_subarray, del_V, freq)
281
+
282
+ # Handle the last index from t=0 to tmax_n
283
+ Jext_subarray = np.array( data.loc[idx_time_zero[-1]:, 'Jext'] )
284
+ errJ_subarray = np.array( data.loc[idx_time_zero[-1]:, 'errJ'] )
285
+ time_subarray = np.array( data.loc[idx_time_zero[-1]:, 't'] )
286
+ cap[-1], errC[-1] = calc_capacitance_forOneVoltage(Jext_subarray, errJ_subarray, time_subarray, del_V, freq)
287
+
288
+ return cap, errC
289
+
290
+ def calc_impedance_limit_time(I, errI, time, VStep, imax):
291
+ """Fourier Decomposition formula which computes the impedance at frequency freq (Hz) and its complex error
292
+ Based on S.E. Laux, IEEE Trans. Electron Dev. 32 (10), 2028 (1985), eq. 5a, 5b
293
+ We integrate from 0 to time[imax] at frequency 1/time[imax]
294
+
295
+ Parameters
296
+ ----------
297
+ I : np.array
298
+ Array of currents
299
+ errI : np.array
300
+ Numerical error in calculated currents (output of ZimT)
301
+ time : np.array
302
+ Array with all time positions, from 0 to tmax
303
+ VStep : float
304
+ Voltage step
305
+ imax : integer
306
+ Index of the last timestep/first frequency for which the integrals are calculated
307
+
308
+ Returns
309
+ -------
310
+ float
311
+ Frequency belonging to Z(f)
312
+ complex number
313
+ Impedance at frequency f: Z(f)
314
+ complex number
315
+ Numerical error in calculated impedance Z(f)
316
+ """
317
+
318
+ freq=1/time[-1] #we obtain the frequency from the time array
319
+ Iinf = I[-1] # I at infinite time, i.e. the last one we have.
320
+ imax = len(I)
321
+ #prepare array for integrants:
322
+ int1 = np.empty(imax)
323
+ int2 = np.empty(imax)
324
+ int3 = np.empty(imax)
325
+ int4 = np.empty(imax)
326
+
327
+ #now we use only part of the time array:
328
+ timeLim = time
329
+ for i,t in enumerate(time) :
330
+ sinfac = math.sin(2*math.pi*freq*timeLim[i])
331
+ cosfac = math.cos(2*math.pi*freq*timeLim[i])
332
+ int1[i] = sinfac*(I[i] - Iinf)
333
+ int2[i] = cosfac*(I[i] - Iinf)
334
+ int3[i] = sinfac*(I[i] + errI[i] - Iinf - errI[-1])
335
+ int4[i] = cosfac*(I[i] + errI[i] - Iinf - errI[-1])
336
+
337
+ #now compute the conductance and capacitance:
338
+ cond = (Iinf - I[0] + 2*math.pi*freq*scipy.integrate.trapezoid(int1, timeLim))/VStep
339
+ cap = scipy.integrate.trapezoid(int2, timeLim)/VStep
340
+ #convert to impedance:
341
+ Z = 1/(cond + 2J*math.pi*freq*cap)
342
+
343
+ #and again, but now with the error added to the current:
344
+ condErr = (Iinf + errI[-1] - I[0] - errI[0] + 2*math.pi*freq*scipy.integrate.trapezoid(int3, timeLim))/VStep
345
+ capErr = scipy.integrate.trapezoid(int4, timeLim)/VStep
346
+ #convert to impedance:
347
+ Z2 = 1/(condErr + 2J*math.pi*freq*capErr)
348
+
349
+ #error is the difference between Z and Z2:
350
+ errZ = Z - Z2
351
+
352
+ #now return complex impedance, its error and the corresponding frequency:
353
+ return freq, Z, errZ
354
+
355
+ def calc_impedance_CV(data, del_V, isToPlot,session_path,zimt_device_parameters,Rseries=0,Rshunt=-1e3):
356
+ """ Calculate the impedance over the frequency range
357
+
358
+ Parameters
359
+ ----------
360
+ data : dataFrame
361
+ Pandas dataFrame containing the time, voltage, current density and numerical error in the current density of the tj_file
362
+ del_V : float
363
+ Voltage step
364
+ isToPlot : list
365
+ List of array indices that will be used in the plotting
366
+
367
+ Returns
368
+ -------
369
+ np.array
370
+ Array of frequencies
371
+ np.array
372
+ Array of the real component of impedance
373
+ np.array
374
+ Array of the imaginary component of impedance
375
+ np.array
376
+ Array of complex error
377
+ np.array
378
+ Array of capacitance
379
+ np.array
380
+ Array of conductance
381
+ np.array
382
+ Array of error in capacitance
383
+ np.array
384
+ Array of error in conductance
385
+ """
386
+ # init the arrays for the impedance and its error:
387
+ numFreqPoints = len(isToPlot)
388
+ # V = np.empty(numFreqPoints)
389
+ ReZ = np.empty(numFreqPoints)
390
+ ImZ = np.empty(numFreqPoints)
391
+ Z = [1 + 1J] * numFreqPoints
392
+ errZ = [1 + 1J] * numFreqPoints
393
+ C = np.empty(numFreqPoints)
394
+ G = np.empty(numFreqPoints)
395
+ errC = np.empty(numFreqPoints)
396
+ errG = np.empty(numFreqPoints)
397
+
398
+
399
+ # We need to know the series and shunt resistance to calculate the impedance correctly later on
400
+ # dev_val,lyrs_dum = load_device_parameters(session_path, zimt_device_parameters)
401
+ # for i in dev_val[zimt_device_parameters]:
402
+ # if i[0] == 'Contacts':
403
+ # contacts = i
404
+ # break
405
+
406
+ # for i in contacts[1:]:
407
+ # if i[1] == 'R_series':
408
+ # Rseries = float(i[2])
409
+ # elif i[1] == 'R_shunt':
410
+ # Rshunt = float(i[2])
411
+
412
+ for i in range(numFreqPoints):
413
+ imax=isToPlot[i]
414
+ if i == 0:
415
+ data_dum = data.loc[0:imax]
416
+ else:
417
+ data_dum = data.loc[isToPlot[i-1]+1:imax]
418
+
419
+ freq, Z[i], errZ[i] = calc_impedance_limit_time(np.asarray(data_dum['Jext']), np.asarray(data_dum['errJ']), np.asarray(data_dum['t']), del_V, imax)
420
+
421
+ if Rseries > 0 and Rshunt > 0:
422
+ # Correct the impedance for the series resistance
423
+ Z[i] = Rseries + 1/(1/Z[i] + 1/Rshunt)
424
+ elif Rseries > 0 and Rshunt < 0:
425
+ # Correct the impedance for the series resistance
426
+ Z[i] = Rseries + Z[i]
427
+ elif Rshunt > 0 and Rseries <= 0:
428
+ # Correct the impedance for the shunt resistance
429
+ invZ = 1/Z[i]
430
+ Z[i] = 1/(invZ + 1/Rshunt)
431
+
432
+ invZ = 1/Z[i]
433
+
434
+ # we are only interested in the absolute value of the real and imag components:
435
+ ReZ[i] = Z[i].real
436
+ ImZ[i] = Z[i].imag
437
+ C[i] = 1/(2*math.pi*freq)*invZ.imag
438
+ G[i] = invZ.real
439
+
440
+ errC[i] = abs(1/(2*math.pi*freq)*(invZ.imag**2)*errZ[i].real)
441
+ errG[i] = abs((invZ.real**2)*errZ[i].imag)
442
+
443
+ return ReZ, ImZ, errZ, C, G, errC, errG
444
+
445
+ def store_capacitance_data(session_path, V, cap, errC, output_file='CapVol.dat'):
446
+ """ Save the capacitance & its error in one file called CapVol.dat
447
+
448
+ Parameters
449
+ ----------
450
+ session_path : string
451
+ working directory for zimt
452
+ V : np.array
453
+ Array of frequencies
454
+ cap : np.array
455
+ Array of the capacitance
456
+ errC : np.array
457
+ Array of the capacitance error
458
+ output_file : string
459
+ Filename where the capacitance data is stored
460
+ """
461
+
462
+ with open(os.path.join(session_path,output_file), 'w') as file:
463
+ file.write('V C errC' + '\n')
464
+ for i in range(len(V)):
465
+ file.write(f'{V[i]:.6e} {cap[i]:.6e} {errC[i]:.6e}' + '\n')
466
+
467
+ def get_capacitance(data, freq, V_0, V_max, del_V, V_step, session_path, zimt_device_parameters, output_file):
468
+ """Calculate the capacitance from the simulation result
469
+
470
+ Parameters
471
+ ----------
472
+ data : DataFrame
473
+ DataFrame with the simulation results (tj.dat) file
474
+ freq : float
475
+ Frequency at which the capacitance-voltage measurement is performed
476
+ V_0 : float
477
+ Initial voltage
478
+ V_max : float
479
+ Maximum voltage
480
+ del_V : float
481
+ Voltage step that is applied directly after t=0
482
+ V_step : float
483
+ Voltage difference, determines at which voltages the capacitance is determined
484
+ session_path : string
485
+ working directory for zimt
486
+ output_file : string
487
+ Filename where the capacitance data is stored
488
+
489
+ Returns
490
+ -------
491
+ integer,string
492
+ returns -1 (failed) or 1 (success), including a message
493
+ """
494
+ # get indexes of the time points where the voltage changes
495
+ isToPlot = data.index[data['t'] == 0]
496
+ # do -1 to get the last index
497
+ isToPlot = isToPlot - 1
498
+ # remove the first index, because we start at t=0
499
+ isToPlot = isToPlot[1:]
500
+ # add the last index to the end
501
+ isToPlot = np.append(isToPlot, len(data['t'])-1)
502
+ V = np.linspace(V_0, V_max, num=math.ceil((V_max-V_0)/V_step)+1, endpoint=True)
503
+
504
+ ReZ, ImZ, errZ, C, G, errC, errG = calc_impedance_CV(data, del_V, isToPlot,session_path, zimt_device_parameters)
505
+
506
+ # Write the capacitance results to a file
507
+ store_capacitance_data(session_path, V, C, errC, output_file)
508
+
509
+ # If the capacitance is calculated, message a success
510
+ msg = 'Success'
511
+ retval = 0
512
+
513
+ return retval, msg
514
+
515
+ def cap_plot(session_path, output_file, xscale='linear', yscale='linear', plot_type = plt.errorbar):
516
+ """ Plot the capacitance against voltage
517
+
518
+ Parameters
519
+ ----------
520
+ session_path : string
521
+ working directory for zimt
522
+ output_file : string
523
+ Filename where the capacitance data is stored
524
+ xscale : string
525
+ Scale of the x-axis. E.g linear or log
526
+ yscale : string
527
+ Scale of the y-axis. E.g linear or log
528
+ plot_type : matplotlib.pyplot
529
+ Type of plot to display
530
+ """
531
+ # Read the data from CapVol-file
532
+ data = pd.read_csv(os.path.join(session_path,output_file), sep=r'\s+')
533
+
534
+ # Define the plot parameters
535
+ fig, ax = plt.subplots()
536
+ pars = {'C' : 'Capacitance' }
537
+ par_x = 'V'
538
+ xlabel = 'Voltage [V]'
539
+ ylabel = 'Capacitance [Fm$^{-2}$]'
540
+ title = 'Capacitance-Voltage'
541
+
542
+ # Plot with or without errorbars
543
+ if plot_type == plt.errorbar:
544
+ ax = utils_plot.plot_result(data, pars, list(pars.keys()), par_x, xlabel, ylabel, xscale, yscale, title, ax, plot_type,
545
+ [], data['errC'], legend=False)
546
+ else:
547
+ ax = utils_plot.plot_result(data, pars, list(pars.keys()), par_x, xlabel, ylabel, xscale, yscale, title, ax, plot_type, legend=False)
548
+
549
+ plt.show()
550
+
551
+ def MottSchottky_plot(session_path, output_file, xscale='linear', yscale='linear', plot_type = plt.errorbar):
552
+ """ Plot the 1/capacitance^2 against voltage
553
+
554
+ Parameters
555
+ ----------
556
+ session_path : string
557
+ working directory for zimt
558
+ output_file : string
559
+ Filename where the capacitance data is stored
560
+ xscale : string
561
+ Scale of the x-axis. E.g linear or log
562
+ yscale : string
563
+ Scale of the y-axis. E.g linear or log
564
+ plot_type : matplotlib.pyplot
565
+ Type of plot to display
566
+ """
567
+ # Read the data from CapVol-file
568
+ data = pd.read_csv(os.path.join(session_path,output_file), sep=r'\s+')
569
+
570
+ # Define the plot parameters
571
+ fig, ax = plt.subplots()
572
+ pars = {'1/C2' : 'Capacitance' }
573
+ par_x = 'V'
574
+ xlabel = 'Voltage [V]'
575
+ ylabel = '1/Capacitance$^2$ [Fm$^{-2}$]$^{-2}$'
576
+ title = 'Mott-Schottky'
577
+
578
+ data['1/C2'] = 1/(data['C'])**2
579
+
580
+ # Plot with or without errorbars
581
+ if plot_type == plt.errorbar:
582
+ ax = utils_plot.plot_result(data, pars, list(pars.keys()), par_x, xlabel, ylabel, xscale, yscale, title, ax, plot_type,
583
+ [], data['errC'], legend=False)
584
+ else:
585
+ ax = utils_plot.plot_result(data, pars, list(pars.keys()), par_x, xlabel, ylabel, xscale, yscale, title, ax, plot_type, legend=False)
586
+
587
+ plt.show()
588
+
589
+ def plot_capacitance(session_path, output_file='CapVol.dat'):
590
+ """Make a plot of the capacitance against voltage and the Mott-Schottky plot
591
+
592
+ Parameters
593
+ ----------
594
+ session_path : string
595
+ working directory for zimt
596
+ """
597
+
598
+ cap_plot(session_path, output_file)
599
+
600
+ MottSchottky_plot(session_path, output_file)
601
+
602
+ def run_CV_simu(zimt_device_parameters, session_path, freq, V_min, V_max, V_step, G_frac=1, del_V=0.01, run_mode=False,tVG_name='tVG.txt', output_file = 'CapVol.dat', tj_name = 'tj.dat', varFile = 'none', ini_timeFactor=1e-3, timeFactor=1.02,**kwargs):
603
+ """Create a tVG file and run ZimT with capacitance device parameters
604
+
605
+ Parameters
606
+ ----------
607
+ zimt_device_parameters : string
608
+ Name of the zimt device parameters file
609
+ session_path : string, optional
610
+ working directory for zimt
611
+ freq : float
612
+ Frequency at which the capacitance-voltage measurement is performed
613
+ V_min : float
614
+ Initial voltage
615
+ V_max : float
616
+ Maximum voltage
617
+ V_step : float
618
+ Voltage difference, determines at which voltages the capacitance is determined
619
+ G_frac : float, optional
620
+ Fractional light intensity, by default 1
621
+ del_V : float, optional
622
+ Voltage step that is applied directly after t=0, by default 0.01
623
+ run_mode : bool, optional
624
+ Indicate whether the script is in 'web' mode (True) or standalone mode (False). Used to control the console output, by default False
625
+ tVG_name : string, optional
626
+ Name of the tVG file, by default tVG.txt
627
+ output_file : string, optional
628
+ Name of the file where the capacitance data is stored, by default CapVol.dat
629
+ tj_name : string, optional
630
+ Name of the tj file where the capacitance data is stored, by default tj.dat
631
+ varFile : string, optional
632
+ Name of the var file, by default 'none'
633
+ ini_timeFactor : float, optional
634
+ Constant defining the size of the initial timestep, by default 1e-3
635
+ timeFactor : float, optional
636
+ Exponential increase of the timestep, to reduce the amount of timepoints necessary. Use values close to 1., by default 1.02
637
+
638
+ Returns
639
+ -------
640
+ CompletedProcess
641
+ Output object of with returncode and console output of the simulation
642
+ string
643
+ Return message to display on the UI, for both success and failed
644
+ """
645
+ UUID = kwargs.get('UUID', '') # Check if the user wants to add a UUID to the tj file name
646
+ cmd_pars = kwargs.get('cmd_pars', None) # Check if the user wants to add additional command line parameters
647
+ # Check if the user wants to force the use of thread safe mode, necessary for Windows with parallel simulations
648
+ if os.name == 'nt':
649
+ threadsafe = kwargs.get('threadsafe', True) # Check if the user wants to force the use of threads instead of processes
650
+ else:
651
+ threadsafe = kwargs.get('threadsafe', False) # Check if the user wants to force the use of threads instead of processes
652
+
653
+ # Update the file names with the UUID
654
+ if UUID != '':
655
+ dum_str = f'_{UUID}'
656
+ else:
657
+ dum_str = ''
658
+
659
+ turnoff_autoTidy = kwargs.get('turnoff_autoTidy', None) # Check if the user wants to turn off the autoTidy function in SIMsalabim
660
+ if turnoff_autoTidy is None:
661
+ if not threadsafe:
662
+ turnoff_autoTidy = True
663
+ else:
664
+ turnoff_autoTidy = False
665
+
666
+ # Update the filenames with the UUID
667
+ tj_name = os.path.join(session_path, tj_name)
668
+ output_file = os.path.join(session_path, output_file)
669
+ tVG_name = os.path.join(session_path, tVG_name)
670
+ if UUID != '':
671
+ tj_file_name_base, tj_file_name_ext = os.path.splitext(tj_name)
672
+ tj_name = tj_file_name_base + dum_str + tj_file_name_ext
673
+ tVG_name_base, tVG_name_ext = os.path.splitext(tVG_name)
674
+ tVG_name = tVG_name_base + dum_str + tVG_name_ext
675
+ output_file_base, output_file_ext = os.path.splitext(output_file)
676
+ output_file = output_file_base + dum_str + output_file_ext
677
+ if varFile != 'none':
678
+ var_file_base, var_file_ext = os.path.splitext(varFile)
679
+ varFile = var_file_base + dum_str + var_file_ext
680
+ varFile = os.path.join(session_path,varFile)
681
+ # varFile = 'none' # we don't use a var file for this simulation
682
+
683
+ # The simulations with Rseries and Rshunt often do not converge, so we first run a steady state simulation to get the internal voltage and then run the impedance simulation with Rseries = 0 and Rshunt = -Rshunt. We will correct the impedance afterwards. This is a workaround to improve the convergence of the impedance simulation that should remain accurate to estimate the impedance.
684
+ #default values for Rseries and Rshunt
685
+ Rseries = 0
686
+ Rshunt = -1e3
687
+
688
+ # Do the steady state simulation to calculate the internal voltage in case of series resistance
689
+ # Create tVG
690
+ result, message = create_tVG_SS_CV(V_min, V_max, V_step, G_frac, tVG_name, session_path)
691
+
692
+ # Get the device parameters and Rseries and Rshunt
693
+ dev_val,layers_dum = load_device_parameters(session_path, zimt_device_parameters)
694
+ for i in dev_val[zimt_device_parameters]:
695
+ if i[0] == 'Contacts':
696
+ contacts = i
697
+ break
698
+
699
+ for i in contacts[1:]:
700
+ if i[1] == 'R_series':
701
+ Rseries = float(i[2])
702
+ elif i[1] == 'R_shunt':
703
+ Rshunt = float(i[2])
704
+
705
+ # Check if R_series and R_shunt are defined in cmd_pars
706
+ idx_Rseries, idx_Rshunt = None, None
707
+ if cmd_pars is not None:
708
+ for idx, i in enumerate(cmd_pars):
709
+ if i['par'] == 'R_series':
710
+ Rseries = float(i['val'])
711
+ idx_Rseries = idx
712
+ elif i['par'] == 'R_shunt':
713
+ Rshunt = float(i['val'])
714
+ idx_Rshunt = idx
715
+
716
+ if Rseries > 0:
717
+ # Check if tVG file is created
718
+ if result == 0:
719
+ # In order for zimt to converge, set absolute tolerance of Poisson solver small enough
720
+ tolPois = 10**(math.floor(math.log10(abs(del_V)))-4)
721
+
722
+ # Define mandatory options for ZimT to run well with impedance:
723
+ CV_SS_args = [{'par':'dev_par_file','val':zimt_device_parameters},
724
+ {'par':'tVGFile','val':tVG_name},
725
+ {'par':'tolPois','val':str(tolPois)},
726
+ {'par':'limitDigits','val':'0'},
727
+ {'par':'currDiffInt','val':'2'},
728
+ {'par':'tJFile','val':tj_name},
729
+ {'par':'varFile','val':varFile},
730
+ {'par':'logFile','val':'log'+dum_str+'.txt'}
731
+ ]
732
+ if turnoff_autoTidy:
733
+ CV_SS_args.append({'par':'autoTidy','val':'0'})
734
+
735
+ if cmd_pars is not None:
736
+ CV_SS_args = update_cmd_pars(CV_SS_args, cmd_pars)
737
+
738
+ if threadsafe:
739
+ result, message = utils_gen.run_simulation_filesafe('zimt', CV_SS_args, session_path, run_mode)
740
+ else:
741
+ result, message = utils_gen.run_simulation('zimt', CV_SS_args, session_path, run_mode)
742
+
743
+ if result.returncode == 0 or result.returncode == 95:
744
+ data = read_tj_file(session_path, tj_file_name=tj_name)
745
+
746
+ Vext = np.asarray(data['Vext'])
747
+ Jext = np.asarray(data['Jext'])
748
+ Vint = Vext - Jext*Rseries
749
+ else:
750
+ return result.returncode, message
751
+ else:
752
+ return result, message
753
+
754
+ # Create tVG
755
+ result, message = create_tVG_CV_Rseries(Vint, del_V, G_frac, tVG_name, session_path, freq, ini_timeFactor, timeFactor)
756
+
757
+ else:
758
+ # Create tVG
759
+ result, message = create_tVG_CV(V_min, V_max, del_V, V_step, G_frac, tVG_name, session_path, freq, ini_timeFactor, timeFactor)
760
+
761
+ # remove the Rseries and Rshunt from cmd_pars
762
+ if idx_Rseries is not None and idx_Rshunt is not None:
763
+ if idx_Rseries < idx_Rshunt:
764
+ cmd_pars.pop(idx_Rshunt)
765
+ cmd_pars.pop(idx_Rseries)
766
+ else:
767
+ cmd_pars.pop(idx_Rseries)
768
+ cmd_pars.pop(idx_Rshunt)
769
+ elif idx_Rseries is not None and idx_Rshunt is None:
770
+ cmd_pars.pop(idx_Rseries)
771
+ elif idx_Rshunt is not None and idx_Rseries is None:
772
+ cmd_pars.pop(idx_Rshunt)
773
+
774
+ # Check if tVG file is created
775
+ if result == 0:
776
+ # In order for zimt to converge, set absolute tolerance of Poisson solver small enough
777
+ tolPois = 10**(math.floor(math.log10(abs(del_V)))-4)
778
+
779
+ # Define mandatory options for ZimT to run well with CV:
780
+ CV_args = [{'par':'dev_par_file','val':zimt_device_parameters},
781
+ {'par':'tVGFile','val':tVG_name},
782
+ {'par':'tolPois','val':str(tolPois)},
783
+ {'par':'limitDigits','val':'0'},
784
+ {'par':'currDiffInt','val':'2'},
785
+ {'par':'tJFile','val':tj_name},
786
+ {'par':'varFile','val':varFile},
787
+ {'par':'logFile','val':'log'+dum_str+'.txt'},
788
+ # We remove Rseries and Rshunt as the simulation is either to converge that way, we will correct the impedance afterwards
789
+ {'par':'R_series','val':str(0)},
790
+ {'par':'R_shunt','val':str(-abs(Rshunt))}]
791
+
792
+ if turnoff_autoTidy:
793
+ CV_args.append({'par':'autoTidy','val':'0'})
794
+
795
+ if cmd_pars is not None:
796
+ CV_args = update_cmd_pars(CV_args, cmd_pars)
797
+
798
+ if threadsafe:
799
+ result, message = utils_gen.run_simulation_filesafe('zimt', CV_args, session_path, run_mode)
800
+ else:
801
+ result, message = utils_gen.run_simulation('zimt', CV_args, session_path, run_mode)
802
+
803
+ if result.returncode == 0 or result.returncode == 95:
804
+ data = read_tj_file(session_path, tj_file_name=tj_name)
805
+
806
+ result, message = get_capacitance(data, freq, V_min, V_max, del_V, V_step, session_path, zimt_device_parameters, output_file)
807
+ return result, message
808
+
809
+ else:
810
+ return result.returncode, message
811
+
812
+ return result, message
813
+
814
+ ######### Running the function as a standalone script #############################################
815
+ if __name__ == "__main__":
816
+ ## Manual CV input parameters. These are overwritten by command line arguments if provided
817
+ freq = 1e4
818
+ V_min = 0.5
819
+ V_max = 1.0
820
+ del_V = 10e-3
821
+ V_step = 0.1
822
+ G_frac = 0
823
+
824
+ # Define folder and file paths
825
+ session_path = os.path.join('../../','SIMsalabim','ZimT')
826
+
827
+ zimt_device_parameters = 'simulation_setup.txt'
828
+
829
+ tVG_name = 'tVG.txt'
830
+ tj_name = 'tj.dat'
831
+ output_name = 'freqZ.dat'
832
+
833
+ # UUID = str(uuid.uuid4()) # Add a UUID to the simulation
834
+ UUID = ''
835
+
836
+ # Not user input
837
+ ini_timeFactor = 1e-3 # Initial timestep factor, org 1e-3
838
+ timeFactor = 1.02 # Increase in timestep every step to reduce the amount of datapoints necessary, use value close to 1 as this is best! Org 1.02
839
+ run_mode = False # If False, show verbose output in console
840
+
841
+ ############## Command line arguments ##############
842
+ ## Notes
843
+ ## - The command line arguments are optional and can be provided in any order
844
+ ## - Each command line argument must be provided in the format -par_name value
845
+ ## - Possible arguments include all SIMsalabim parameters and CV specific parameters as listed before
846
+ ## - Special arguments
847
+ ## - sp : string
848
+ ## - The session path, i.e. the working directory for the simulation
849
+ ## - simsetup : string
850
+ ## - The name of the zimt simulation setup parameters file
851
+ ## - UUID : string
852
+ ## - An UUID to add to the simulation (output)
853
+
854
+ cmd_pars_dict = {}
855
+ cmd_pars = []
856
+
857
+ # Check if any arguments are provided.
858
+ if len(sys.argv) >= 2:
859
+ # Each arguments should be in the format -par val, i.e. in pairs of two. Skip the first argument as this is the script name
860
+ if not len(sys.argv[1:]) % 2 == 0:
861
+ print('Error in command line parameters. Please provide arguments in the format -par_name value -par_name value ...')
862
+ sys.exit(1)
863
+ else:
864
+ input_list = sys.argv[1:]
865
+ # Loop over the input list and put pairs into a dictionary with the first argument as key and the second argument as value
866
+ for i in range(0,len(input_list),2):
867
+ # Check if the key already exists, if not, add it to the cmd_pars_dict
868
+ if str(input_list[i][1:]) in cmd_pars_dict:
869
+ print(f'Duplicate parameter found in the command line parameters: {str(input_list[i][1:])}')
870
+ sys.exit(1)
871
+ else:
872
+ cmd_pars_dict[str(input_list[i][1:])] = str(input_list[i+1])
873
+
874
+ # Check and process specific keys/arguments that are not native SIMsalabim arguments
875
+ # Handle the session_path/sp argument separately, as the other parameters depend on this
876
+ if 'sp' in cmd_pars_dict:
877
+ session_path = cmd_pars_dict['sp']
878
+ # remove from cmd_pars
879
+ cmd_pars_dict.pop('sp')
880
+
881
+ # Define mappings for keys and variables
882
+ key_action_map = {
883
+ 'simsetup': lambda val: {'zimt_device_parameters': val},
884
+ 'freq': lambda val: {'freq': float(val)},
885
+ 'V_min': lambda val: {'V_min': float(val)},
886
+ 'V_max': lambda val: {'V_max': float(val)},
887
+ 'del_V': lambda val: {'del_V': float(val)},
888
+ 'V_step': lambda val: {'V_step': float(val)},
889
+ 'G_frac': lambda val: {'G_frac': float(val)},
890
+ 'tVG_name': lambda val: {'tVG_name': val},
891
+ 'tj_name': lambda val: {'tj_name': val},
892
+ 'out_name': lambda val: {'output_name': val},
893
+ 'UUID': lambda val: {'UUID': val},
894
+ }
895
+
896
+ for key in list(cmd_pars_dict.keys()): # Use list to avoid modifying the dictionary while iterating
897
+ if key in key_action_map:
898
+ # Apply the corresponding action
899
+ result = key_action_map[key](cmd_pars_dict[key])
900
+ globals().update(result) # Dynamically update global variables
901
+ cmd_pars_dict.pop(key)
902
+
903
+ # Handle remaining keys in `cmd_pars_dict` and add them to the cmd_pars list
904
+ cmd_pars.extend({'par': key, 'val': value} for key, value in cmd_pars_dict.items())
905
+
906
+ # Run Capacitance-Voltage
907
+ result, message = run_CV_simu(zimt_device_parameters, session_path, freq, V_min, V_max, V_step, G_frac, del_V,run_mode=False, tVG_name=tVG_name,
908
+ output_file = output_name, tj_name = tj_name, ini_timeFactor=ini_timeFactor, timeFactor=timeFactor, cmd_pars=cmd_pars, UUID=UUID)
909
+
910
+ # Make the capacitance-voltage plot
911
+ if result == 0 or result == 95:
912
+ plot_capacitance(session_path, os.path.basename(output_name))
913
+ else:
914
+ print(message)
915
+ sys.exit(1)
916
+
917
+
918
+