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,753 @@
1
+ """Perform JV hysteresis 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 pySIMsalabim
9
+ ## Import pySIMsalabim, if not successful, add the parent directory to the system path
10
+ try :
11
+ import pySIMsalabim as sim
12
+ except ImportError:
13
+ # Add the parent directory to the system path
14
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
15
+ import pySIMsalabim as sim
16
+ from pySIMsalabim.utils import general as utils_gen
17
+ from pySIMsalabim.plots import plot_functions as utils_plot
18
+ from pySIMsalabim.utils.utils import update_cmd_pars
19
+
20
+ ######### Function Definitions ####################################################################
21
+
22
+ def build_tVG_arrays(Vmin,Vmax,scan_speed,direction,steps,G_frac):
23
+ """Build the Arrays for time, voltage and Generation rate for a hysteresis experiment.
24
+
25
+ Parameters
26
+ ----------
27
+ Vmin : float
28
+ minimum voltage
29
+ Vmax : float
30
+ maximum voltage
31
+ scan_speed : float
32
+ Voltage scan speed [V/s]
33
+ direction : integer
34
+ Perform a Vmin-Vmax-Vmin (1) or Vmax-Vmin-Vmax scan (-1)
35
+ steps : integer
36
+ Number of time steps
37
+ G_frac : float
38
+ Device Parameter | Fractional Generation rate
39
+
40
+ Returns
41
+ -------
42
+ np.array
43
+ Array of time points
44
+ np.array
45
+ Array of voltages
46
+ np.array
47
+ Array of generation rates
48
+ """
49
+ # Determine max time point
50
+ tmax = abs((Vmax - Vmin)/scan_speed)
51
+ V, G = [], []
52
+ Vmin_ = Vmin
53
+ Vmax_ = Vmax
54
+
55
+ if direction == -1:
56
+ Vmin = Vmax_
57
+ Vmax = Vmin_
58
+
59
+ t_min_to_max = np.linspace(0,tmax,int(steps/2))
60
+ t_max_to_min = np.linspace(tmax,2*tmax,int(steps/2))
61
+ t_max_to_min = np.delete(t_max_to_min,[0]) # remove double entry
62
+ t = np.append(t_min_to_max,t_max_to_min)
63
+
64
+ for i in t:
65
+ if i < tmax:
66
+ # First voltage sweep
67
+ V.append(direction*scan_speed*i + Vmin)
68
+ else:
69
+ # Second voltage sweep
70
+ V.append(-direction*scan_speed*(i-tmax) + Vmax)
71
+ # Append the generation rate
72
+ G.append(G_frac)
73
+ # convert to numpy arrays
74
+ V, G = np.asarray(V), np.asarray(G)
75
+ return t,V,G
76
+
77
+ def build_tVG_arrays_log(Vmin,Vmax,scan_speed,direction,steps,G_frac,Vminexpo= 1e-2):
78
+ """Build the Arrays for time, voltage and Generation rate for a hysteresis experiment with an exponential voltage sweep.
79
+
80
+ Parameters
81
+ ----------
82
+ Vmin : float
83
+ minimum voltage
84
+ Vmax : float
85
+ maximum voltage
86
+ scan_speed : float
87
+ Voltage scan speed [V/s]
88
+ direction : integer
89
+ Perform a Vmin-Vmax-Vmin (1) or Vmax-Vmin-Vmax scan (-1)
90
+ steps : integer
91
+ Number of time steps
92
+ G_frac : float
93
+ Device Parameter | Fractional Generation rate
94
+ Vminexpo : float
95
+ Voltage at which the exponential voltage steps start if Vmin or Vmax is 0
96
+
97
+ Returns
98
+ -------
99
+ np.array
100
+ Array of time points
101
+ np.array
102
+ Array of voltages
103
+ np.array
104
+ Array of generation rates
105
+ """
106
+
107
+ if Vmin*Vmax >= 0:
108
+ if Vmin == 0:
109
+ V_min_to_max = np.logspace(np.log10(abs(Vminexpo)),np.log10(abs(Vmax)),int(steps/2))
110
+ # add 0 to the beginning of the array
111
+ V_min_to_max = np.insert(V_min_to_max,0,0)
112
+ elif Vmax == 0:
113
+ V_min_to_max = np.logspace(np.log10(abs(Vmin)),np.log10(abs(Vminexpo)),int(steps/2))
114
+ # add 0 to the end of the array
115
+ V_min_to_max = np.append(V_min_to_max,0)
116
+ else:
117
+ if Vmin > 0:
118
+ V_min_to_max = np.logspace(np.log10(abs(Vmin)),np.log10(abs(Vmax)),int(steps/2))
119
+ else:
120
+ V_min_to_max = -np.logspace(np.log10(abs(Vmax)),np.log10(abs(Vmin)),int(steps/2))
121
+
122
+ V_max_to_min = V_min_to_max[::-1]
123
+
124
+
125
+ # Create t,G arrays for both sweep directions
126
+ if direction == 1:
127
+ # forward -> backward
128
+ V_max_to_min = np.delete(V_max_to_min,[0])# remove double entry
129
+ V = np.append(V_min_to_max,V_max_to_min)
130
+
131
+ elif direction == -1:
132
+ # backward -> forward
133
+ V_min_to_max = np.delete(V_min_to_max,[0])# remove double entry
134
+ V = np.append(V_max_to_min,V_min_to_max)
135
+
136
+ G = G_frac * np.ones(len(V))
137
+
138
+ # calculate the time array based on the voltage array and the scan speed
139
+ t = np.zeros(len(V))
140
+ for i in range(1,len(V)):
141
+ t[i] = t[i-1] + abs((V[i]-V[i-1])/scan_speed)
142
+
143
+ else:
144
+ negative_V = -np.logspace(np.log10(abs(Vmin)),np.log10(abs(Vminexpo)),int(steps/4))
145
+ positive_V = np.logspace(np.log10(abs(Vminexpo)),np.log10(abs(Vmax)),int(steps/4))
146
+ # add 0 at the beginning
147
+ positive_V = np.append(0,positive_V)
148
+ V = np.append(negative_V,positive_V)
149
+ # make back to back
150
+ Vback = V[::-1]
151
+
152
+ if direction == 1:
153
+ # remove the first element
154
+ Vback = Vback[1:]
155
+ V = np.append(V,Vback)
156
+ G = G_frac * np.ones(len(V))
157
+ elif direction == -1:
158
+ # remove the last element
159
+ Vback = Vback[:-1]
160
+ V = np.append(Vback,V)
161
+ G = G_frac * np.ones(len(V))
162
+
163
+ # calculate the time array based on the voltage array and the scan speed
164
+ t = np.zeros(len(V))
165
+ for i in range(1,len(V)):
166
+ t[i] = t[i-1] + abs((V[i]-V[i-1])/scan_speed)
167
+ return t,V,G
168
+
169
+ def create_tVG_hysteresis(session_path, Vmin, Vmax, scan_speed, direction, steps, G_frac, tVG_name, **kwargs):
170
+ """Create a tVG file for hysteresis experiments.
171
+
172
+ Parameters
173
+ ----------
174
+ session_path : string
175
+ working directory for zimt
176
+ Vmin : float
177
+ Left voltage boundary
178
+ Vmax : float
179
+ Right voltage boundary
180
+ scan_speed : float
181
+ Voltage scan speed [V/s]
182
+ direction : integer
183
+ Perform a Vmin-Vmax-Vmin (1) or Vmax-Vmin-Vmax scan (-1)
184
+ steps : integer
185
+ Number of time steps
186
+ G_frac : float
187
+ Device Parameter | Fractional Generation rate
188
+ tVG_name : string
189
+ Device Parameter | Name of the tVG file
190
+ **kwargs : dict
191
+ Additional keyword arguments
192
+
193
+ Returns
194
+ -------
195
+ integer
196
+ Value to indicate the result of the process
197
+ string
198
+ A message to indicate the result of the process
199
+ """
200
+ # kwargs
201
+ expo_mode = kwargs.get('expo_mode', False) # whether to use exponential voltage steps
202
+ Vminexpo = kwargs.get('Vminexpo', 1e-2) # Voltage at which the exponential voltage steps start if Vmin or Vmax is 0
203
+ # check that Vminexpo is positive
204
+ if Vminexpo <= 0:
205
+ msg = 'Vminexpo must be strictly positive'
206
+ retval = 1
207
+ return retval, msg
208
+
209
+ # check that direction is either 1 or -1
210
+ if direction != 1 and direction != -1:
211
+ msg = 'Incorrect scan direction, choose either 1 for a forward - backward scan or -1 for a backward - forward scan'
212
+ retval = 1
213
+ return retval, msg
214
+
215
+ # check that Vmin < Vmax
216
+ if Vmin >= Vmax:
217
+ msg = 'Vmin must be smaller than Vmax'
218
+ retval = 1
219
+ return retval, msg
220
+
221
+ # Create two arrays for both time sweeps
222
+ if expo_mode:
223
+ t,V,G = build_tVG_arrays_log(Vmin,Vmax,scan_speed,direction,steps,G_frac,Vminexpo)
224
+ else:
225
+ t,V,G = build_tVG_arrays(Vmin,Vmax,scan_speed,direction,steps,G_frac)
226
+
227
+ # Set the correct header for the tVG file
228
+ tVG_header = ['t','Vext','G_frac']
229
+
230
+ # Combine t,V,G arrays into a DataFrame
231
+ tVG = pd.DataFrame(np.stack([t,np.asarray(V),np.asarray(G)]).T,columns=tVG_header)
232
+
233
+ # Create tVG file
234
+ tVG.to_csv(os.path.join(session_path,tVG_name),sep=' ',index=False,float_format='%.5e')
235
+
236
+ # tVG file is created, msg a success
237
+ msg = 'Success'
238
+ retval = 0
239
+
240
+ return retval, msg
241
+
242
+ def plot_hysteresis_JV(path2file = 'tj.dat'):
243
+ """Plot the hysteresis JV curve
244
+
245
+ Parameters
246
+ ----------
247
+ path2file : string
248
+ Path to the tj file
249
+
250
+ Returns
251
+ -------
252
+ Axes
253
+ Axes object for the plot
254
+
255
+ """
256
+ # Read the data from tj-file
257
+ data_tj = pd.read_csv(path2file, sep=r'\s+')
258
+
259
+ fig, ax = plt.subplots()
260
+ pars = {'Jext' : 'Simulation'} #'$J_{ext}$'}
261
+ par_x = 'Vext'
262
+ xlabel = '$V_{ext}$ [V]'
263
+ ylabel = 'Current density [Am$^{-2}$]'
264
+ xscale = 'linear'
265
+ yscale = 'linear'
266
+ title = 'JV curve'
267
+ plot_type = plt.plot
268
+
269
+ ax = utils_plot.plot_result(data_tj, pars, list(pars.keys()), par_x, xlabel, ylabel, xscale, yscale, title, ax, plot_type)
270
+
271
+ return ax
272
+
273
+ def tVG_exp(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin, scan_speed, direction, G_frac, tVG_name):
274
+ """Create a tVG file for hysteresis experiments where Vext is the same as the voltages in the experimental JV file
275
+
276
+ Parameters
277
+ ----------
278
+ session_path : string
279
+ working directory for zimt
280
+ expJV_Vmin_Vmax : string
281
+ Name of the file of the Vmin-Vmax JV scan
282
+ expJV_Vmax_Vmin : string
283
+ Name of the file of the Vmax-Vmin JV scan
284
+ scan_speed : float
285
+ Voltage scan speed [V/s]
286
+ direction : integer
287
+ Perform a Vmin-Vmax-Vmin (1) or Vmax-Vmin-Vmax scan (-1)
288
+ G_frac : float
289
+ Fractional Generation rate
290
+ tVG_name : string
291
+ Name of the tVG file
292
+
293
+ Returns
294
+ -------
295
+ integer
296
+ Value to indicate the result of the process
297
+ string
298
+ A message to indicate the result of the process
299
+ """
300
+
301
+ if direction == 1:
302
+ JV_forward, JV_backward = read_Exp_JV(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin)
303
+ elif direction == -1:
304
+ JV_backward, JV_forward = read_Exp_JV(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin)
305
+ else:
306
+ # Illegal value for direction given
307
+ msg = 'Incorrect scan direction, choose either 1 for Vmin-Vmax-Vmin scan or -1 for a Vmax-Vmin-Vmax scan'
308
+ retval = 1
309
+ return retval, msg
310
+
311
+ V_forward = JV_forward.Vext
312
+ V_backward = JV_backward.Vext
313
+
314
+ # Create the time array
315
+ t=np.empty(len(V_forward) + len(V_backward))
316
+ t[0]=0
317
+
318
+ # First half
319
+ for i in range(1,len(V_forward)):
320
+ t[i]= t[i-1] + abs((V_forward[i]-V_forward[i-1])/scan_speed)
321
+
322
+ # Turning point
323
+ t[len(V_forward)]=t[len(V_forward)-1] + abs((V_backward[0]-V_forward.iloc[-1])/scan_speed)
324
+
325
+ # Second half
326
+ for i in range(len(V_forward)+1,len(V_forward) + len(V_backward)):
327
+ t[i]= t[i-1] + abs((V_backward[i-len(V_forward)]-V_backward[i-len(V_forward)-1])/scan_speed)
328
+
329
+ # Voltage array
330
+ V = np.concatenate([V_forward, V_backward])
331
+
332
+ # Set the correct header for the tVG file
333
+ tVG_header = ['t','Vext','G_frac']
334
+
335
+ G = G_frac * np.ones(len(t))
336
+
337
+ # Combine t,V,G arrays into a DataFrama
338
+ tVG = pd.DataFrame(np.stack([t,np.asarray(V),G]).T,columns=tVG_header)
339
+
340
+ # Create tVG file
341
+ tVG.to_csv(os.path.join(session_path,tVG_name),sep=' ',index=False,float_format='%.3e')
342
+
343
+ # tVG file is created, msg a success
344
+ msg = 'Success'
345
+ retval = 0
346
+ return retval, msg
347
+
348
+ def read_Exp_JV(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin):
349
+ """Read experimental forward and backward JV files
350
+
351
+ Parameters
352
+ ----------
353
+ session_path : string
354
+ working directory for zimt
355
+ expJV_Vmin_Vmax : string
356
+ Name of the file of the forward JV scan
357
+ expJV_Vmax_Vmin : string
358
+ Name of the file of the backward JV scan
359
+
360
+ Returns
361
+ -------
362
+ np.array
363
+ Array of current and voltage of experimental JV from Vmin to Vmax
364
+ np.array
365
+ Array of current and voltage of experimental JV from Vmax to Vmin
366
+ """
367
+
368
+ expJV_min_max = os.path.join(session_path, expJV_Vmin_Vmax)
369
+ expJV_max_min = os.path.join(session_path, expJV_Vmax_Vmin)
370
+
371
+ # Determine time corresponding to each voltage V_i
372
+ JV_min_max = pd.read_csv(expJV_min_max, sep=r'\s+')
373
+ JV_max_min = pd.read_csv(expJV_max_min, sep=r'\s+')
374
+
375
+ return JV_min_max, JV_max_min
376
+
377
+ def concatJVs(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin, direction):
378
+ """Put the experimental forward and backward JV arrays together
379
+
380
+ Parameters
381
+ ----------
382
+ session_path : string
383
+ working directory for zimt
384
+ expJV_Vmin_Vmax : string
385
+ Name of the file of the forward JV scan
386
+ expJV_Vmax_Vmin : string
387
+ Name of the file of the backward JV scan
388
+ direction : integer
389
+ Perform a Vmin-Vmax-Vmin (1) or Vmax-Vmin-Vmax scan (-1)
390
+
391
+ Returns
392
+ -------
393
+ np.array
394
+ Array of current and voltage of experimental JV
395
+ """
396
+
397
+ if direction == 1:
398
+ JV_forward, JV_backward = read_Exp_JV(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin)
399
+ elif direction == -1:
400
+ JV_backward, JV_forward = read_Exp_JV(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin)
401
+ else:
402
+ # Illegal value for direction given
403
+ print('Incorrect scan direction, choose either 1 for Vmin-Vmax-Vmin scan or -1 for a Vmax-Vmin-Vmax scan')
404
+ sys.exit()
405
+
406
+ expJV = pd.concat([JV_forward, JV_backward], ignore_index=True)
407
+ return expJV
408
+
409
+ def read_tj_file(session_path, tj_file_name='tj.dat'):
410
+ """ Read relevant parameters for admittance of the tj file
411
+
412
+ Parameters
413
+ ----------
414
+ session_path : string
415
+ Path of the simulation folder for this session
416
+ data_tj : dataFrame
417
+ Pandas dataFrame containing the tj output file from ZimT
418
+
419
+ Returns
420
+ -------
421
+ DataFrame
422
+ Pandas dataFrame of the tj_file containing the time, current density, numerical error in the current density and the photogenerated current density
423
+ """
424
+
425
+ data = pd.read_csv(os.path.join(session_path,tj_file_name), sep=r'\s+')
426
+
427
+ return data
428
+
429
+ def Compare_Exp_Sim_JV(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin, rms_mode, direction, tj_file_name='tj.dat'):
430
+ """ Calculate the root-mean-square (rms) error of the simulated data compared to the experimental data. The used formulas are
431
+ described in the Manual (see the variable rms_mode in the section 'Description of simulated device parameters').
432
+
433
+ Parameters
434
+ ----------
435
+ session_path : string
436
+ Path of the simulation folder for this session
437
+ expJV_Vmin_Vmax : string
438
+ Name of the file of the forward JV scan
439
+ expJV_Vmax_Vmin : string
440
+ Name of the file of the backward JV scan
441
+ rms_mode : string
442
+ Indicates how the normalised rms error should be calculated: either in linear or logarithmic form
443
+ direction : integer
444
+ Perform a Vmin-Vmax-Vmin (1) or Vmax-Vmin-Vmax scan (-1)
445
+ tj_file_name : dataFrame
446
+ Pandas dataFrame containing the tj output file from ZimT
447
+
448
+ Returns
449
+ -------
450
+ Float
451
+ Calculated rms-error
452
+ """
453
+
454
+ JVExp = concatJVs(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin, direction)
455
+ JVSim = read_tj_file(session_path, tj_file_name)[['t', 'Vext', 'Jext']]
456
+
457
+ # Make an array of voltages that did not converge in simulation
458
+ V_array_not_in_JVSim = np.setdiff1d(JVExp.Vext, JVSim.Vext)
459
+
460
+ # Remove voltages of experimental data that did not converge in the simulation
461
+ # As the rms-value cannot be calculated, when the voltages of the simulation and experimental data do not overlap
462
+ if len(V_array_not_in_JVSim) > 0:
463
+ disgardedPoints = True
464
+ indices = []
465
+
466
+ for i in range(len(V_array_not_in_JVSim)):
467
+ # Find indices where voltages do not overlap for every V_i
468
+ index_array = np.where((JVExp.Vext == V_array_not_in_JVSim[i]))[0]
469
+
470
+ # Add the to-slice-indices to a list
471
+ for j in range(len(index_array)):
472
+ indices.append(index_array[j])
473
+
474
+ # Delete the indices and convert JVExp from a numpy array in a DataFrame again
475
+ JVExp = np.delete(JVExp, np.sort(indices), axis=0)
476
+ JVExp = pd.DataFrame(JVExp, columns=['Vext', 'Jext'])
477
+
478
+ rms = 0
479
+ count = 0
480
+ disgardedPoints = False
481
+
482
+ # Look for the interval [Jmin,Jmax] in both the simulated and experiment data
483
+ Jmin = min(min(JVExp.Jext), min(JVSim.Jext))
484
+ Jmax = max(max(JVExp.Jext), max(JVSim.Jext))
485
+
486
+ if rms_mode == 'lin' or 'linear':
487
+ # Calculate the sum of squared residuals
488
+ for i in range(len(JVExp)):
489
+ rms = rms + (JVExp.Jext[i] - JVSim.Jext[i])**2
490
+ count += 1
491
+
492
+ # Calculate the root mean square error and normalise with respect to the interval [Jmin,Jmax]
493
+ rms = np.sqrt(rms/count)/(Jmax-Jmin)
494
+
495
+ elif rms_mode == 'log' or 'logarithmic':
496
+ # Calculate the sum of squared residuals
497
+ for i in range(len(JVExp)):
498
+ if JVExp.Jext[i]*JVSim.Jext[i]>=0: # We can only calc rms if both are <> 0 and they have the same sign
499
+ rms = rms + np.log(JVExp.Jext[i]/JVSim.Jext[i])**2
500
+ else:
501
+ disgardedPoints = True
502
+
503
+ # Calculate the root mean square error and normalise with respect to the interval [Jmin,Jmax]
504
+ rms = np.sqrt(rms/count)/abs(np.log(abs(Jmax/Jmin))) # Note: Jmax > Jmin, of course, but ABS(Jmin) can be larger than ABS(Jmax) so we need to use ABS(LN(...)) to get a positive rms
505
+
506
+ if disgardedPoints:
507
+ print('Not all JV points were used in computing the rms-error.')
508
+ print('Delete voltages are: ', V_array_not_in_JVSim)
509
+
510
+ return rms
511
+
512
+ def Hysteresis_JV(zimt_device_parameters, session_path, UseExpData, scan_speed, direction, G_frac, tVG_name='tVG.txt', tj_name = 'tj.dat',varFile='none',
513
+ run_mode=False, Vmin=0.0, Vmax=0.0, steps =0, expJV_Vmin_Vmax='', expJV_Vmax_Vmin='',rms_mode='lin', **kwargs ):
514
+ """Create a tVG file and perform a JV hysteresis experiment.
515
+
516
+ Parameters
517
+ ----------
518
+ zimt_device_parameters : string
519
+ name of the zimt device parameters file
520
+ session_path : string
521
+ working directory for zimt
522
+ UseExpData : integer
523
+ If 1, use experimental JV curves. If 0, Use Vmin, Vmax as boundaries
524
+ scan_speed : float
525
+ Voltage scan speed [V/s]
526
+ direction : integer
527
+ Perform a forward-backward (1) or backward-forward scan (-1).
528
+ G_frac : float
529
+ Device Parameter | Fractional generation rate
530
+ run_mode : bool, optional
531
+ Indicate whether the script is in 'web' mode (True) or standalone mode (False). Used to control the console output, by default False
532
+ tVG_name : string, optional
533
+ Device Parameter | Name of the tVG file, by default 'tVG.txt'
534
+ tj_name : string, optional
535
+ Name of the tj file, by default 'tj.dat'
536
+ varFile : string, optional
537
+ Name of the var file, by default 'none'
538
+ run_mode : bool, optional
539
+ indicate whether the script is in 'web' mode (True) or standalone mode (False). Used to control the console output, by default False
540
+ Vmin : float, optional
541
+ Left voltage boundary, by default 0.0
542
+ Vmax : float, optional
543
+ Right voltage boundary, by default 0.0
544
+ steps : int, optional
545
+ Number of time steps, by default 0
546
+ expJV_Vmin_Vmax : str, optional
547
+ file name of the first expJV curve, by default ''
548
+ expJV_Vmax_Vmin : str, optional
549
+ file name of the second expJV curve, by default ''
550
+ rms_mode : str, optional
551
+ Either 'lin' or 'log' to specify how the rms error is calculated
552
+
553
+ Returns
554
+ -------
555
+ CompletedProcess
556
+ Output object of with returncode and console output of the simulation
557
+ string
558
+ Return message to display on the UI, for both success and failed
559
+ rms
560
+ The rms error between the simulated and experimental data. WHen not using experimental data, it is set to 0.0 and can be ignored
561
+ """
562
+
563
+ UUID = kwargs.get('UUID', '') # Check if the user wants to add a UUID to the tj file name
564
+ cmd_pars = kwargs.get('cmd_pars', None) # Check if the user wants to add additional command line parameters
565
+ # Check if the user wants to force the use of thread safe mode, necessary for Windows with parallel simulations
566
+ if os.name == 'nt':
567
+ threadsafe = kwargs.get('threadsafe', True) # Check if the user wants to force the use of threads instead of processes
568
+ else:
569
+ threadsafe = kwargs.get('threadsafe', False) # Check if the user wants to force the use of threads instead of processes
570
+
571
+ turnoff_autoTidy = kwargs.get('turnoff_autoTidy', None) # Check if the user wants to turn off the autoTidy function in SIMsalabim
572
+ if turnoff_autoTidy is None:
573
+ if not threadsafe:
574
+ turnoff_autoTidy = True
575
+ else:
576
+ turnoff_autoTidy = False
577
+
578
+ # tVG file generation additional parameters
579
+ expo_mode = kwargs.get('expo_mode', False) # whether to use exponential time steps
580
+ Vminexpo = kwargs.get('Vminexpo', 1e-2) # minimum voltage after 0 to start the log steps
581
+
582
+ # Update the JV file name with the UUID
583
+ if UUID != '':
584
+ dum_str = f'_{UUID}'
585
+ else:
586
+ dum_str = ''
587
+
588
+ # Update the filenames with the UUID
589
+ tj_name = os.path.join(session_path, tj_name)
590
+ tVG_name = os.path.join(session_path, tVG_name)
591
+ if UUID != '':
592
+ tj_file_name_base, tj_file_name_ext = os.path.splitext(tj_name)
593
+ tj_name = tj_file_name_base + dum_str + tj_file_name_ext
594
+ tVG_name_base, tVG_name_ext = os.path.splitext(tVG_name)
595
+ tVG_name = tVG_name_base + dum_str + tVG_name_ext
596
+ if varFile != 'none':
597
+ var_file_base, var_file_ext = os.path.splitext(varFile)
598
+ varFile = var_file_base + dum_str + var_file_ext
599
+ varFile = os.path.join(session_path, varFile)
600
+ # varFile = 'none' # we don't use a var file for the hysteresis JV simulation
601
+
602
+ rms = 0.0
603
+ if UseExpData == 1:
604
+ # When fitting to experimental data, create a tVG file where Vext is the same as the voltages in the experimental JV file
605
+ if os.path.exists(os.path.join(session_path, expJV_Vmin_Vmax)) and os.path.exists(os.path.join(session_path, expJV_Vmax_Vmin)):
606
+ result, message = tVG_exp(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin, scan_speed, direction, G_frac, tVG_name)
607
+ else:
608
+ result = 1
609
+ message = 'Experimental JV files not found'
610
+ else:
611
+ result, message = create_tVG_hysteresis(session_path, Vmin, Vmax, scan_speed, direction, steps, G_frac, tVG_name, expo_mode=expo_mode, Vminexpo=Vminexpo)
612
+
613
+ if result == 0:
614
+ # tVG file created
615
+ Hysteresis_JV_args = [{'par':'dev_par_file','val':zimt_device_parameters},
616
+ {'par':'tVGFile','val':tVG_name},
617
+ {'par':'tJFile','val':tj_name},
618
+ {'par':'varFile','val':varFile},
619
+ {'par':'logFile','val':'log'+dum_str+'.txt'}
620
+ ]
621
+
622
+ if turnoff_autoTidy:
623
+ Hysteresis_JV_args.append({'par':'autoTidy','val':'0'})
624
+
625
+ if cmd_pars is not None:
626
+ Hysteresis_JV_args = update_cmd_pars(Hysteresis_JV_args, cmd_pars)
627
+
628
+ if threadsafe:
629
+ result, message = utils_gen.run_simulation_filesafe('zimt', Hysteresis_JV_args, session_path, run_mode)
630
+ else:
631
+ result, message = utils_gen.run_simulation('zimt', Hysteresis_JV_args, session_path, run_mode)
632
+
633
+ if result.returncode == 0 or result.returncode == 95:
634
+ if UseExpData == 1:
635
+ rms = Compare_Exp_Sim_JV(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin, rms_mode, direction, tj_name)
636
+ result = result.returncode
637
+
638
+ return result, message, rms
639
+
640
+ ## Running the function as a standalone script
641
+ if __name__ == "__main__":
642
+ ## Manual Hysteresis input parameters. These are overwritten by command line arguments if provided
643
+ scan_speed = 1e1 # V/s
644
+ direction = 1 # Scan direction: 1 for Vmin-Vmax-Vmin, -1 for Vmax-Vmin-Vmax
645
+ G_frac = 1 # amount of suns
646
+ UseExpData = 0 # integer, if 1 read experimental data
647
+ Vmin = 0 # lower voltage boundary
648
+ Vmax = 1.15 # upper voltage boundary
649
+ steps = 1000 # Number of voltage steps
650
+ expJV_Vmin_Vmax = 'od05_f.txt' # Forward (direction=1)/Backward (direction=-1) JV scan file
651
+ expJV_Vmax_Vmin = 'od05_b.txt' # Backward (direction=1)/Forward (direction=-1) JV scan file
652
+
653
+ # Define folder and file paths
654
+ session_path = os.path.join('../../','SIMsalabim','ZimT')
655
+
656
+ zimt_device_parameters = 'simulation_setup.txt'
657
+
658
+ tVG_name = 'tVG.txt'
659
+ tj_name = 'tj.dat'
660
+
661
+ # UUID = str(uuid.uuid4()) # Add a UUID to the simulation
662
+ UUID = ''
663
+
664
+ # Not user input
665
+ rms_mode = 'log' # lin or log
666
+
667
+ ############## Command line arguments ##############
668
+ ## Notes
669
+ ## - The command line arguments are optional and can be provided in any order
670
+ ## - Each command line argument must be provided in the format -par_name value
671
+ ## - Possible arguments include all SIMsalabim parameters and Hysteresis JV specific parameters as listed before
672
+ ## - Special arguments
673
+ ## - sp : string
674
+ ## - The session path, i.e. the working directory for the simulation
675
+ ## - simsetup : string
676
+ ## - The name of the zimt simulation setup parameters file
677
+ ## - UUID : string
678
+ ## - An UUID to add to the simulation (output)
679
+
680
+ cmd_pars_dict = {}
681
+ cmd_pars = []
682
+
683
+ # Check if any arguments are provided.
684
+ if len(sys.argv) >= 2:
685
+ # 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
686
+ if not len(sys.argv[1:]) % 2 == 0:
687
+ print('Error in command line parameters. Please provide arguments in the format -par_name value -par_name value ...')
688
+ sys.exit(1)
689
+ else:
690
+ input_list = sys.argv[1:]
691
+ # Loop over the input list and put pairs into a dictionary with the first argument as key and the second argument as value
692
+ for i in range(0,len(input_list),2):
693
+ # Check if the key already exists, if not, add it to the cmd_pars_dict
694
+ if str(input_list[i][1:]) in cmd_pars_dict:
695
+ print(f'Duplicate parameter found in the command line parameters: {str(input_list[i][1:])}')
696
+ sys.exit(1)
697
+ else:
698
+ cmd_pars_dict[str(input_list[i][1:])] = str(input_list[i+1])
699
+
700
+ # Check and process specific keys/arguments that are not native SIMsalabim arguments
701
+ # Handle the session_path/sp argument separately, as the other parameters depend on this
702
+ if 'sp' in cmd_pars_dict:
703
+ session_path = cmd_pars_dict['sp']
704
+ # remove from cmd_pars
705
+ cmd_pars_dict.pop('sp')
706
+
707
+ # Define mappings for keys and variables
708
+ key_action_map = {
709
+ 'simsetup': lambda val: {'zimt_device_parameters': val},
710
+ 'scan_speed': lambda val: {'scan_speed': float(val)},
711
+ 'direction': lambda val: {'direction': int(val)},
712
+ 'G_frac': lambda val: {'G_frac': float(val)},
713
+ 'UseExpData': lambda val: {'UseExpData': int(val)},
714
+ 'Vmin': lambda val: {'Vmin': float(val)},
715
+ 'Vmax': lambda val: {'Vmax': float(val)},
716
+ 'steps': lambda val: {'steps': int(val)},
717
+ 'expJV_Vmin_Vmax': lambda val: {'expJV_Vmin_Vmax': val},
718
+ 'expJV_Vmax_Vmin': lambda val: {'expJV_Vmax_Vmin': val},
719
+ 'tVG_name': lambda val: {'tVG_name': val},
720
+ 'tj_name': lambda val: {'tj_name': val},
721
+ 'UUID': lambda val: {'UUID': val},
722
+ }
723
+
724
+ for key in list(cmd_pars_dict.keys()): # Use list to avoid modifying the dictionary while iterating
725
+ if key in key_action_map:
726
+ # Apply the corresponding action
727
+ result = key_action_map[key](cmd_pars_dict[key])
728
+ globals().update(result) # Dynamically update global variables
729
+ cmd_pars_dict.pop(key)
730
+
731
+ # Handle remaining keys in `cmd_pars_dict` and add them to the cmd_pars list
732
+ cmd_pars.extend({'par': key, 'val': value} for key, value in cmd_pars_dict.items())
733
+
734
+ if UseExpData == 1:
735
+ result, message, rms = Hysteresis_JV(zimt_device_parameters, session_path, UseExpData, scan_speed, direction, G_frac, tVG_name = tVG_name, tj_name = tj_name,
736
+ run_mode = False, expJV_Vmin_Vmax = expJV_Vmin_Vmax, expJV_Vmax_Vmin = expJV_Vmax_Vmin, rms_mode = rms_mode, cmd_pars = cmd_pars, UUID=UUID)
737
+ else:
738
+ result, message, rms = Hysteresis_JV(zimt_device_parameters, session_path, UseExpData, scan_speed, direction, G_frac, tVG_name = tVG_name, tj_name = tj_name,
739
+ run_mode = False, Vmin=Vmin, Vmax=Vmax, steps =steps, rms_mode = rms_mode, cmd_pars = cmd_pars, UUID=UUID)
740
+
741
+ if result == 0 or result == 95:
742
+ if UseExpData == 1:
743
+ print('Rms-value: ', "{:.5f}".format(round(rms, 5)))
744
+
745
+ ax = plot_hysteresis_JV(tj_name)
746
+ if UseExpData == 1:
747
+ JVExp = concatJVs(session_path, expJV_Vmin_Vmax, expJV_Vmax_Vmin, direction)
748
+ ax.scatter(JVExp.Vext, JVExp.Jext, label='Experimental', color='r')
749
+
750
+ ax.legend()
751
+ plt.show()
752
+ else:
753
+ print('Convergence issues, no plot is printed')