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,630 @@
1
+ """Perform Intensity-Modulated Photocurrent Spectroscopy (IMPS) 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_IMPS(V, G_frac, del_G, tVG_name, session_path, f_min, f_max, ini_timeFactor, timeFactor):
26
+ """Create a tVG file for IMPS experiments.
27
+
28
+ Parameters
29
+ ----------
30
+ V : float
31
+ Voltage, the voltage is constant over the whole time range
32
+ G_frac : float
33
+ Fractional light intensity
34
+ del_G : float
35
+ Applied generation rate increase at t=0
36
+ tVG_name : string
37
+ Name of the tVG file
38
+ session_path : string
39
+ Path of the simulation folder for this session
40
+ f_min : float
41
+ Minimum frequency
42
+ f_max : float
43
+ Maximum frequency
44
+ ini_timeFactor : float
45
+ Constant defining the size of the initial timestep
46
+ timeFactor : float
47
+ Exponential increase of the timestep, to reduce the amount of timepoints necessary. Use values close to 1.
48
+
49
+ Returns
50
+ -------
51
+ string
52
+ A message to indicate the result of the process
53
+ """
54
+
55
+ time = 0
56
+ del_t = ini_timeFactor/f_max
57
+
58
+ # Starting line of the tVG file: header + datapoints at time=0. Set the correct header
59
+ tVG_lines = 't Vext G_frac\n' + f'{time:.3e} {V} {G_frac:.3e}\n'
60
+
61
+ # Make the other lines in the tVG file
62
+ while time < 1/f_min: #max time: 1/f_min is enough!
63
+ time = time+del_t
64
+ tVG_lines += f'{time:.3e} {V} {G_frac+del_G:.3e}\n'
65
+ del_t = del_t * timeFactor # At first, we keep delt constant to its minimum values
66
+
67
+ # Export tVG file to ZimT folder
68
+ with open(os.path.join(session_path,tVG_name), 'w') as file:
69
+ file.write(tVG_lines)
70
+
71
+ # tVG file is created, message a success
72
+ msg = 'Success'
73
+ retval = 0
74
+ return retval, msg
75
+
76
+ # def read_tj_file(session_path, tj_file_name='tj.dat'):
77
+ # """ Read relevant parameters for admittance of the tj file
78
+
79
+ # Parameters
80
+ # ----------
81
+ # session_path : string
82
+ # Path of the simulation folder for this session
83
+ # data_tj : dataFrame
84
+ # Pandas dataFrame containing the tj output file from ZimT
85
+
86
+ # Returns
87
+ # -------
88
+ # DataFrame
89
+ # Pandas dataFrame of the tj_file containing the time, current density, numerical error in the current density and the photogenerated current density
90
+ # """
91
+
92
+ # data = pd.read_csv(os.path.join(session_path,tj_file_name), sep=r'\s+')
93
+
94
+ # return data
95
+
96
+ # def get_integral_bounds(data, f_min=1e-2, f_max=1e6, f_steps=20):
97
+ # """ Determine integral bounds in the time domain, used to compute the conductance and capacitance
98
+
99
+ # Parameters
100
+ # ----------
101
+ # data : dataFrame
102
+ # Pandas dataFrame containing the time, current density, numerical error in the current density and the photogenerated current density of the tj_file
103
+ # f_min : float
104
+ # Minimum frequency
105
+ # f_max : float
106
+ # Maximum frequency
107
+ # f_steps : float
108
+ # Frequency steps
109
+
110
+ # Returns
111
+ # -------
112
+ # list
113
+ # List of array indices that will be used in the plotting
114
+ # """
115
+
116
+ # # Total number of time points
117
+ # numTimePoints = len(data['t'])
118
+
119
+ # # Check which time index corresponds to 1/fmax. We call this istart:
120
+ # istart = -1
121
+ # for i in range(numTimePoints):
122
+ # if math.isclose(data['t'][i], 1/f_max, rel_tol = 2/f_steps): #note: don't use == to compare 2 floating points!
123
+ # istart = i
124
+
125
+ # # Starting time point could not be found
126
+ # if istart == -1:
127
+ # msg = 'Could not find a time that corresponds to the highest frequency.'
128
+ # return -1, msg
129
+
130
+ # # print('Found istart: ', istart)
131
+
132
+ # # ifin: last index we should plot, corresponds to time = 1/f_min:
133
+ # ifin = numTimePoints - 1
134
+
135
+ # # isToPlot starts with istart:
136
+ # isToPlot = [istart]
137
+
138
+ # PlotRatio = max(1, round( (ifin-istart)/(math.log10(f_max/f_min) * f_steps)))
139
+
140
+ # # Incorrect plot ratio
141
+ # if PlotRatio < 1:
142
+ # msg = 'PlotRatio smaller than 1. It should at least be 1'
143
+ # return -1, msg
144
+
145
+ # # Then add the other indices:
146
+ # for i in range(istart+1, ifin-1):
147
+ # if (i-istart) % PlotRatio == 0: # note: % is python's modulo operator.
148
+ # isToPlot.append(i) # add the index to our array
149
+
150
+ # # Also include the last index:
151
+ # isToPlot.append(ifin)
152
+
153
+ # # Integral bounds have been determined, return the array with indices and a success message
154
+ # msg = 'Success'
155
+ # return isToPlot, msg
156
+
157
+ def calc_IMPS_limit_time(I, errI, time, imax):
158
+ """Fourier Decomposition formula which computes the admittance at frequency freq (Hz) and its complex error
159
+ Based on S.E. Laux, IEEE Trans. Electron Dev. 32 (10), 2028 (1985), eq. 5a, 5b
160
+ We integrate from 0 to time[imax] at frequency 1/time[imax]
161
+
162
+ Parameters
163
+ ----------
164
+ I : np.array
165
+ Array of currents
166
+ errI : np.array
167
+ Numerical error in calculated currents (output of ZimT)
168
+ time : np.array
169
+ Array with all time positions, from 0 to tmax
170
+ imax : integer
171
+ Index of the last timestep/first frequency for which the integrals are calculated
172
+
173
+ Returns
174
+ -------
175
+ float
176
+ Frequency belonging to Y(f)
177
+ complex number
178
+ Admittance at frequency f: Y(f)
179
+ complex number
180
+ Numerical error in calculated admittance Y(f)
181
+ """
182
+
183
+ freq=1/time[imax] #we obtain the frequency from the time array
184
+ Iinf = I[imax] # I at infinite time, i.e. the last one we have.
185
+
186
+ #prepare array for integrants:
187
+ int1 = np.empty(imax)
188
+ int2 = np.empty(imax)
189
+ int3 = np.empty(imax)
190
+ int4 = np.empty(imax)
191
+
192
+ #now we use only part of the time array:
193
+ timeLim = time[0:imax]
194
+
195
+ for i in range(imax) :
196
+ sinfac = math.sin(2*math.pi*freq*timeLim[i])
197
+ cosfac = math.cos(2*math.pi*freq*timeLim[i])
198
+ int1[i] = sinfac*(I[i] - Iinf)
199
+ int2[i] = cosfac*(I[i] - Iinf)
200
+ int3[i] = sinfac*(I[i] + errI[i] - Iinf - errI[imax])
201
+ int4[i] = cosfac*(I[i] + errI[i] - Iinf - errI[imax])
202
+
203
+ #now compute the conductance and capacitance:
204
+ cond = (Iinf - I[0] + 2*math.pi*freq*scipy.integrate.trapezoid(int1, timeLim))
205
+ cap = scipy.integrate.trapezoid(int2, timeLim)
206
+ #convert to admittance:
207
+ Y = cond + 2J*math.pi*freq*cap
208
+
209
+ #and again, but now with the error added to the current:
210
+ condErr = (Iinf + errI[imax] - I[0] - errI[0] + 2*math.pi*freq*scipy.integrate.trapezoid(int3, timeLim))
211
+ capErr = scipy.integrate.trapezoid(int4, timeLim)
212
+ #convert to admittance:
213
+ Y2 = condErr + 2J*math.pi*freq*capErr
214
+
215
+ #error is the difference between Y and Y2:
216
+ errY = Y - Y2
217
+
218
+ #now return complex admittance, its error and the corresponding frequency:
219
+ return freq, Y, errY
220
+
221
+ def calc_IMPS(data, isToPlot):
222
+ """ Calculate the admittance over the frequency range
223
+
224
+ Parameters
225
+ ----------
226
+ data : dataFrame
227
+ Pandas dataFrame containing the time, current density, numerical error in the current density and the photogenerated current density of the tj_file
228
+ isToPlot : list
229
+ List of array indices that will be used in the plotting
230
+
231
+ Returns
232
+ -------
233
+ np.array
234
+ Array of frequencies
235
+ np.array
236
+ Array of the real component of admittance
237
+ np.array
238
+ Array of the imaginary component of admittance
239
+ np.array
240
+ Array of complex error
241
+ """
242
+ # init the arrays for the admittance and its error:
243
+ numFreqPoints = len(isToPlot)
244
+ freq = np.empty(numFreqPoints)
245
+ ReY = np.empty(numFreqPoints)
246
+ ImY = np.empty(numFreqPoints)
247
+ Y = [1 + 1J] * numFreqPoints
248
+ errY = [1 + 1J] * numFreqPoints
249
+
250
+ for i in range(numFreqPoints):
251
+ imax=isToPlot[i]
252
+ freq[i], Y[i], errY[i] = calc_IMPS_limit_time(data['Jext'], data['errJ'], data['t'], imax)
253
+ # we are only interested in the absolute value of the real and imag components:
254
+ ReY[i] =(Y[i].real)
255
+ ImY[i] = (Y[i].imag)
256
+
257
+ return freq, ReY, ImY, errY
258
+
259
+ def store_IMPS_data(session_path, freq, ReY, ImY, errY, output_file):
260
+ """ Save the frequency, real & imaginary part of the admittance & its error in one file called freqY.dat
261
+
262
+ Parameters
263
+ ----------
264
+ session_path : string
265
+ working directory for zimt
266
+ freq : np.array
267
+ Array of frequencies
268
+ ReY : np.array
269
+ Array of the real component of admittance
270
+ ImY : np.array
271
+ Array of the imaginary component of admittance
272
+ errY : np.array
273
+ Array of complex error in admittance
274
+ """
275
+
276
+ with open(os.path.join(session_path,output_file), 'w') as file:
277
+ file.write('freq ReY ImY ReErrY ImErrY' + '\n')
278
+ for i in range(len(freq)):
279
+ file.write(f'{freq[i]:.6e} {ReY[i]:.6e} {ImY[i]:.6e} {abs(errY[i].real):.6e} {abs(errY[i].imag):.6e}' + '\n')
280
+
281
+ # print('The data of the IMPS graphs is written to ' + output_file)
282
+
283
+ def get_IMPS(data, f_min, f_max, f_steps, session_path, output_file):
284
+ """Calculate the IMPS from the simulation result
285
+
286
+ Parameters
287
+ ----------
288
+ data : DataFrame
289
+ DataFrame with the simulation results (tj.dat) file
290
+ f_min : float
291
+ Minimum frequency
292
+ f_max : float
293
+ Maximum frequency
294
+ f_steps : float
295
+ Frequency step
296
+ session_path : string
297
+ working directory for zimt
298
+ output_file : string
299
+ name of the file where the IMPS data is stored
300
+
301
+ Returns
302
+ -------
303
+ integer,string
304
+ returns -1 (failed) or 1 (success), including a message
305
+ """
306
+ isToPlot, msg = get_integral_bounds(data, f_min, f_max, f_steps)
307
+
308
+ if isToPlot != -1:
309
+ # Integral bounds have been determined, continue to calculate the IMPS
310
+ freq, ReY, ImY, errY = calc_IMPS(data, isToPlot)
311
+
312
+ # Write IMPS results to a file
313
+ store_IMPS_data(session_path, freq, ReY, ImY, errY, output_file)
314
+
315
+ msg = 'Success'
316
+ return 0, msg
317
+ else:
318
+ # Failed to determine integral bounds, exit with the error message
319
+ return -1, msg
320
+
321
+ def IMPS_plot(session_path, output_file, xscale='log', yscale='log', plot_type = plt.plot):
322
+ """ Plot the real and imaginary part of the admittance against frequency
323
+
324
+ Parameters
325
+ ----------
326
+ session_path : string
327
+ working directory for zimt
328
+ xscale : string
329
+ Scale of the x-axis. E.g linear or log
330
+ yscale_ax1 : string
331
+ Scale of the left y-axis. E.g linear or log
332
+ yscale_ax2 : string
333
+ Scale of the right y-axis. E.g linear or log
334
+ """
335
+ # Read the data from freqY-file
336
+ data_freqY = pd.read_csv(os.path.join(session_path,output_file), sep=r'\s+')
337
+
338
+ # Flip the ImY data to the first quadrant
339
+ # data["ImY"] = data["ImY"]*-1*-1
340
+
341
+ # Define the plot parameters, two y axis
342
+ pars_imps = {'ImY' : '-Im Y [A/m$^2$]' }
343
+ selected = ['ImY']
344
+ par_x = 'freq'
345
+ xlabel = 'frequency [Hz]'
346
+ ylabel = 'Im Y'
347
+ title = 'Computed IMPS'
348
+ fig, ax = plt.subplots()
349
+ utils_plot.plot_result(data_freqY, pars_imps, selected, par_x, xlabel, ylabel, xscale, yscale, title, ax, plot_type)
350
+
351
+ plt.show()
352
+
353
+ def ColeCole_plot(session_path, output_file, xscale='linear', yscale='linear', plot_type = plt.errorbar):
354
+ """ Plot the Cole-Cole plot with the real and imaginary part of the admittance against frequency
355
+
356
+ Parameters
357
+ ----------
358
+ session_path : string
359
+ working directory for zimt
360
+ output_file : string
361
+ Filename where the admittance data is stored
362
+ xscale : string
363
+ Scale of the x-axis. E.g linear or log
364
+ yscale : string
365
+ Scale of the y-axis. E.g linear or log
366
+ plot_type : matplotlib.pyplot
367
+ Type of plot to display
368
+ """
369
+ # Read the data from freqY-file
370
+ data = pd.read_csv(os.path.join(session_path,output_file), sep=r'\s+')
371
+
372
+ fig, ax = plt.subplots()
373
+ pars_nyq = {'ImY' : '-Im Y [A/m$^2$]'}
374
+ par_x_nyq = 'ReY'
375
+ par_weight_nyq = 'freq'
376
+ xlabel_nyq = 'Re Y [A/m$^2$]'
377
+ ylabel_nyq = '-Im Y [A/m$^2$]'
378
+ weightlabel_nyq = 'frequency [Hz]'
379
+ weight_norm_nyq = 'log'
380
+ title_nyq = 'Cole-Cole plot'
381
+
382
+ # Plot the Cole-Cole plot with or without errorbars
383
+ if plot_type == plt.errorbar:
384
+ ax = utils_plot.plot_result(data, pars_nyq, list(pars_nyq.keys()), par_x_nyq, xlabel_nyq, ylabel_nyq, xscale, yscale, title_nyq, ax, plot_type,
385
+ [], data['ImErrY'], legend=False)
386
+ else:
387
+ ax = utils_plot.plot_result(data, pars_nyq, list(pars_nyq.keys()), par_x_nyq, xlabel_nyq, ylabel_nyq, xscale, yscale, title_nyq, ax, plot_type, legend=False)
388
+
389
+ plt.show()
390
+
391
+
392
+
393
+ def plot_IMPS(session_path, output_file='freqY.dat'):
394
+ """Plot admittance of IMPS
395
+
396
+ Parameters
397
+ ----------
398
+ session_path : string
399
+ working directory for zimt
400
+ """
401
+ # IMPS plot
402
+ IMPS_plot(session_path,output_file)
403
+
404
+ # Cole-Cole plot
405
+ ColeCole_plot(session_path,output_file)
406
+
407
+ def run_IMPS_simu(zimt_device_parameters, session_path, f_min, f_max, f_steps, V, G_frac, GStep = 0.05, run_mode=False, tVG_name = 'tVG.txt', output_file = 'freqY.dat', tj_name = 'tj.dat',varFile ='none', ini_timeFactor=1e-3, timeFactor=1.02, **kwargs):
408
+ """Create a tVG file and run ZimT with admittance device parameters
409
+
410
+ Parameters
411
+ ----------
412
+ zimt_device_parameters : string
413
+ Name of the zimt device parameters file
414
+ session_path : string
415
+ Path of the simulation folder for this session
416
+ f_min : float
417
+ Minimum frequency
418
+ f_max : float
419
+ Maximum frequency
420
+ f_steps : float
421
+ Frequency step
422
+ V : float
423
+ Voltage, the voltage is constant over the whole time range
424
+ G_frac : float
425
+ Fractional light intensity
426
+ GStep : float, optional
427
+ Applied generation rate increase at t=0, by default 0.05
428
+ run_mode : bool, optional
429
+ Indicate whether the script is in 'web' mode (True) or standalone mode (False). Used to control the console output, by default False
430
+ tVG_name : string, optional
431
+ Name of the tVG file, by default tVG.txt
432
+ output_file : string, optional
433
+ Name of the file where the admittance data is stored, by default freqY.dat
434
+ tj_name : string, optional
435
+ Name of the tj file where the admittance data is stored, by default tj.dat
436
+ varFile : string, optional
437
+ Name of the var file, by default 'none'
438
+ ini_timeFactor : float, optional
439
+ Constant defining the size of the initial timestep, by default 1e-3
440
+ timeFactor : float, optional
441
+ Exponential increase of the timestep, to reduce the amount of timepoints necessary. Use values close to 1., by default 1.02
442
+
443
+ Returns
444
+ -------
445
+ CompletedProcess
446
+ Output object of with returncode and console output of the simulation
447
+ string
448
+ Return message to display on the UI, for both success and failed
449
+ """
450
+ UUID = kwargs.get('UUID', '') # Check if the user wants to add a UUID to the tj file name
451
+ cmd_pars = kwargs.get('cmd_pars', None) # Check if the user wants to add additional command line parameters
452
+ # Check if the user wants to force the use of thread safe mode, necessary for Windows with parallel simulations
453
+ if os.name == 'nt':
454
+ threadsafe = kwargs.get('threadsafe', True) # Check if the user wants to force the use of threads instead of processes
455
+ else:
456
+ threadsafe = kwargs.get('threadsafe', False) # Check if the user wants to force the use of threads instead of processes
457
+
458
+ turnoff_autoTidy = kwargs.get('turnoff_autoTidy', None) # Check if the user wants to turn off the autoTidy function in SIMsalabim
459
+ if turnoff_autoTidy is None:
460
+ if not threadsafe:
461
+ turnoff_autoTidy = True
462
+ else:
463
+ turnoff_autoTidy = False
464
+
465
+ # Update the file names with the UUID
466
+ if UUID != '':
467
+ dum_str = f'_{UUID}'
468
+ else:
469
+ dum_str = ''
470
+
471
+ # Update the filenames with the UUID
472
+ tj_name = os.path.join(session_path, tj_name)
473
+ output_file = os.path.join(session_path, output_file)
474
+ tVG_name = os.path.join(session_path, tVG_name)
475
+ if UUID != '':
476
+ tj_file_name_base, tj_file_name_ext = os.path.splitext(tj_name)
477
+ tj_name = tj_file_name_base + dum_str + tj_file_name_ext
478
+ tVG_name_base, tVG_name_ext = os.path.splitext(tVG_name)
479
+ tVG_name = tVG_name_base + dum_str + tVG_name_ext
480
+ output_file_base, output_file_ext = os.path.splitext(output_file)
481
+ output_file = output_file_base + dum_str + output_file_ext
482
+ if varFile != 'none':
483
+ var_file_base, var_file_ext = os.path.splitext(varFile)
484
+ varFile = var_file_base + dum_str + var_file_ext
485
+ varFile = os.path.join(session_path,varFile)
486
+ # varFile = 'none' # we don't use a var file for this simulation
487
+
488
+ # Create tVG
489
+ result, message = create_tVG_IMPS(V, G_frac, GStep, tVG_name, session_path, f_min, f_max, ini_timeFactor, timeFactor)
490
+
491
+ # Check if tVG file is created
492
+ if result == 0:
493
+ # Define mandatory options for ZimT to run well with IMPS:
494
+ IMPS_args = [{'par':'dev_par_file','val':zimt_device_parameters},
495
+ {'par':'tVGFile','val':tVG_name},
496
+ {'par':'limitDigits','val':'0'},
497
+ {'par':'currDiffInt','val':'2'},
498
+ {'par':'tJFile','val':tj_name},
499
+ {'par':'varFile','val':varFile},
500
+ {'par':'logFile','val':'log'+dum_str+'.txt'}]
501
+
502
+ if turnoff_autoTidy:
503
+ IMPS_args.append({'par':'autoTidy','val':'0'})
504
+
505
+ if cmd_pars is not None:
506
+ IMPS_args = update_cmd_pars(IMPS_args, cmd_pars)
507
+
508
+ if threadsafe:
509
+ result, message = utils_gen.run_simulation_filesafe('zimt', IMPS_args, session_path, run_mode)
510
+ else:
511
+ result, message = utils_gen.run_simulation('zimt', IMPS_args, session_path, run_mode)
512
+
513
+ if result.returncode == 0 or result.returncode == 95:
514
+ data = read_tj_file(session_path, tj_file_name=tj_name)
515
+
516
+ result, message = get_IMPS(data, f_min, f_max, f_steps, session_path, output_file)
517
+ return result, message
518
+
519
+ else:
520
+ return result.returncode, message
521
+
522
+ return result, message
523
+
524
+ ## Running the function as a standalone script
525
+ if __name__ == "__main__":
526
+ # IMPS input parameters
527
+ f_min = 1e-2 # org 1e-2
528
+ f_max = 5e6# org 1e6
529
+ f_steps = 30 # org 30
530
+ V_0 = 1.0 # Float or 'oc' for the open-circuit voltage
531
+ G_frac = 1
532
+ fac_G = 5e-2 # org 2e-1, use around 0.2 for IMPS
533
+
534
+ # Define folder and file paths
535
+ session_path = os.path.join('../../','SIMsalabim','ZimT')
536
+
537
+ zimt_device_parameters = 'simulation_setup.txt'
538
+
539
+ tVG_name = 'tVG.txt'
540
+ tj_name = 'tj.dat'
541
+ output_name = 'freqZ.dat'
542
+
543
+ # UUID = str(uuid.uuid4()) # Add a UUID to the simulation
544
+ UUID = ''
545
+
546
+ # Not user input
547
+ ini_timeFactor = 1e-3 # Initial timestep factor, org 1e-3
548
+ 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
549
+ run_mode = False # If False, show verbose output in console
550
+
551
+ ############## Command line arguments ##############
552
+ ## Notes
553
+ ## - The command line arguments are optional and can be provided in any order
554
+ ## - Each command line argument must be provided in the format -par_name value
555
+ ## - Possible arguments include all SIMsalabim parameters and IMPS specific parameters as listed before
556
+ ## - Special arguments
557
+ ## - sp : string
558
+ ## - The session path, i.e. the working directory for the simulation
559
+ ## - simsetup : string
560
+ ## - The name of the zimt simulation setup parameters file
561
+ ## - UUID : string
562
+ ## - An UUID to add to the simulation (output)
563
+
564
+ cmd_pars_dict = {}
565
+ cmd_pars = []
566
+
567
+ # Check if any arguments are provided.
568
+ if len(sys.argv) >= 2:
569
+ # 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
570
+ if not len(sys.argv[1:]) % 2 == 0:
571
+ print('Error in command line parameters. Please provide arguments in the format -par_name value -par_name value ...')
572
+ sys.exit(1)
573
+ else:
574
+ input_list = sys.argv[1:]
575
+ # Loop over the input list and put pairs into a dictionary with the first argument as key and the second argument as value
576
+ for i in range(0,len(input_list),2):
577
+ # Check if the key already exists, if not, add it to the cmd_pars_dict
578
+ if str(input_list[i][1:]) in cmd_pars_dict:
579
+ print(f'Duplicate parameter found in the command line parameters: {str(input_list[i][1:])}')
580
+ sys.exit(1)
581
+ else:
582
+ cmd_pars_dict[str(input_list[i][1:])] = str(input_list[i+1])
583
+
584
+ # Check and process specific keys/arguments that are not native SIMsalabim arguments
585
+ # Handle the session_path/sp argument separately, as the other parameters depend on this
586
+ if 'sp' in cmd_pars_dict:
587
+ session_path = cmd_pars_dict['sp']
588
+ # remove from cmd_pars
589
+ cmd_pars_dict.pop('sp')
590
+
591
+ # Define mappings for keys and variables
592
+ key_action_map = {
593
+ 'simsetup': lambda val: {'zimt_device_parameters': val},
594
+ 'f_min': lambda val: {'f_min': float(val)},
595
+ 'f_max': lambda val: {'f_max': float(val)},
596
+ 'f_steps': lambda val: {'f_steps': int(val)},
597
+ 'V_0': lambda val: {'V_0': float(val)},
598
+ 'G_frac': lambda val: {'G_frac': float(val)},
599
+ 'fac_G': lambda val: {'fac_G': float(val)},
600
+ 'tVG_name': lambda val: {'tVG_name': val},
601
+ 'tj_name': lambda val: {'tj_name': val},
602
+ 'out_name': lambda val: {'output_name': val},
603
+ 'UUID': lambda val: {'UUID': val},
604
+ }
605
+
606
+ for key in list(cmd_pars_dict.keys()): # Use list to avoid modifying the dictionary while iterating
607
+ if key in key_action_map:
608
+ # Apply the corresponding action
609
+ result = key_action_map[key](cmd_pars_dict[key])
610
+ globals().update(result) # Dynamically update global variables
611
+ cmd_pars_dict.pop(key)
612
+
613
+ # Handle remaining keys in `cmd_pars_dict` and add them to the cmd_pars list
614
+ cmd_pars.extend({'par': key, 'val': value} for key, value in cmd_pars_dict.items())
615
+
616
+
617
+ # Run IMPS spectroscopy
618
+ GStep = G_frac*fac_G
619
+
620
+ # result, message = run_IMPS_simu(zimt_device_parameters, f_min, f_max, f_steps, V, G_frac, GStep, tVG_name=tVG_name, session_path= session_path, run_mode=False, ini_timeFactor=ini_timeFactor, timeFactor=timeFactor)
621
+ result, message = run_IMPS_simu(zimt_device_parameters,session_path, f_min, f_max, f_steps, V_0, G_frac, GStep, run_mode=False, tVG_name=tVG_name,
622
+ output_file = output_name, tj_name = tj_name, ini_timeFactor=ini_timeFactor, timeFactor=timeFactor, cmd_pars=cmd_pars, UUID=UUID)
623
+
624
+ # Make the IMPS plots
625
+ if result == 0 or result == 95:
626
+ plot_IMPS(session_path, os.path.basename(output_name))
627
+ else:
628
+ print(message)
629
+ sys.exit(1)
630
+
@@ -0,0 +1,20 @@
1
+ import os
2
+ import importlib.util
3
+ import pkgutil
4
+
5
+ # Path to the directory of this file
6
+ package_dir = os.path.dirname(__file__)
7
+
8
+ # Loop through all modules in the current directory
9
+ for (_, module_name, _) in pkgutil.iter_modules([package_dir]):
10
+ # Construct the full path to the module
11
+ module_path = os.path.join(package_dir, module_name + '.py')
12
+ # Import the module
13
+ spec = importlib.util.spec_from_file_location(module_name, module_path)
14
+ module = importlib.util.module_from_spec(spec)
15
+ spec.loader.exec_module(module)
16
+ # Add all functions from the module to globals() so they can be imported directly
17
+ for attribute_name in dir(module):
18
+ attribute = getattr(module, attribute_name)
19
+ if callable(attribute):
20
+ globals()[attribute_name] = attribute