-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamidr.py
2292 lines (1917 loc) · 125 KB
/
amidr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 4 07:44:54 2021
@ Original AMID Author: Marc M. E. Cormier
@ Current AMIDR Author: Mitchell Ball
"""
import pandas as pd
import numpy as np
import sys
from scipy.optimize import curve_fit, fsolve
from scipy import stats
from pathlib import Path
import re
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import warnings
warnings.filterwarnings(action = 'ignore')
plt.rc('lines', markersize = 4, linewidth = 0.75)
plt.rc('axes', grid = True, labelsize = 14)
plt.rc('axes.grid', which = 'both')
plt.rc('grid', color = 'grey')
plt.rc('xtick.minor', bottom = True, top = False)
plt.rc('ytick.minor', left = True, right = False)
plt.rc('xtick', bottom = True, top = False, direction = 'out', labelsize = 10)
plt.rc('ytick', left = True, right = False, direction = 'out', labelsize = 10)
plt.rc('legend', frameon = False, fontsize = 10, columnspacing = 1.0, handletextpad = 0.5, handlelength = 1.4)
plt.rc('errorbar', capsize = 2)
plt.rc('savefig', dpi = 300)
RATES = np.array([0.01, 0.05, 0.1, 0.2, 1/3, 0.5, 1, 2, 2.5, 5, 10, 20, 40, 80, 160, 320, 640, 1280])
COLUMNS = ['Time', 'Cycle', 'Step', 'Current', 'Potential', 'Capacity', 'Prot_step']
UNITS = ['(h)', None, None, '(mA)', '(V)', '(mAh)', None]
SHAPES = ['sphere']
class BIOCONVERT():
def __init__(self, path, form_files, d_files, c_files, cellname, export_data = True, export_fig = True):
print("_________________________________")
# Acquire header info from first file
all_files = []
all_files.extend(form_files)
all_files.extend(d_files)
all_files.extend(c_files)
firstFileLoc = Path(path) / all_files[0]
with open(firstFileLoc, 'r') as f:
# Read beginning of first file to discover lines in header
f.readline()
hlinenum = int(f.readline().strip().split()[-1])
header = f.readlines()[:hlinenum-3]
# Acquire protocol name, capacity, active mass, and time started
protText = re.search('Loaded Setting File : (.+)', ''.join(header))
protName = protText.group(1).strip()
massText = re.search('Mass of active material : (\d+.?\d+) (.+)', ''.join(header))
massVal = float(massText.group(1))
massUnit = massText.group(2).strip()
if massUnit != 'mg':
print("Mass Unit: " + massUnit)
print("Please edit first file to express mass in mg so that specific capacity is accurately calculated.\n")
capacityText = re.search('Battery capacity : (\d+.?\d+) (.+)', ''.join(header))
capacityVal = float(capacityText.group(1))
capacityUnit = capacityText.group(2).strip()
if capacityUnit != 'mA.h':
print("Capacity Unit: " + capacityUnit + "100")
print("Please edit first file to express capacity in mA.h so that specific capacity and rates are accurately calculated.\n")
capacityUnit = capacityUnit.replace('.h', 'Hr')
startText = re.search('Technique started on : (.+)', ''.join(header))
startTime = startText.group(1).strip()
# Write header text
csvHeader = '[Summary]\nCell: ' + cellname + '\nFirst Protocol: ' + protName \
+ '\nMass (' + massUnit + '): ' + str(massVal) + '\nCapacity (' + capacityUnit + '): ' + str(capacityVal) \
+ '\nStarted: ' + startTime + '\n[End Summary]\n[Data]\n'
# Generate complete csv
df = pd.DataFrame({})
# Generate form dataframe if data available
if form_files:
dfForm = pd.DataFrame({})
# Read and combine form file data
for f in form_files:
formFileLoc = Path(path) / f
with open(formFileLoc, 'r') as f:
# Read beginning of form file to discover lines in header
f.readline()
hlinenum = int(f.readline().strip().split()[-1]) - 1
# Read file into dataframe and convert to UHPC format
dfTempForm = pd.read_csv(formFileLoc, skiprows = hlinenum, sep = '\t', encoding_errors = 'replace')
dfTempForm = dfTempForm[['mode', 'time/s', 'I/mA', 'Ewe-Ece/V', 'Ewe/V', '(Q-Qo)/mA.h', 'Ns']]
# Convert to NVX initial step convention
dfTempForm['Ns'] = dfTempForm['Ns'] + 1
# Add last previous capacity, time, and step number to current data
if not(dfForm.empty):
dfTempForm['time/s'] = dfTempForm['time/s'] + dfForm['time/s'].iat[-1]
dfTempForm['(Q-Qo)/mA.h'] = dfTempForm['(Q-Qo)/mA.h'] + dfForm['(Q-Qo)/mA.h'].iat[-1]
dfTempForm['Ns'] = dfTempForm['Ns'] + dfForm['Ns'].iat[-1]
# Concatenate
dfForm = pd.concat([dfForm, dfTempForm])
# Convert to hours, base units, NVX labels, and NVX rest step convention while retaining order
dfForm['time/s'] = dfForm['time/s'] / 3600
dfForm['I/mA'] = dfForm['I/mA'] / 1000
dfForm['(Q-Qo)/mA.h'] = dfForm['(Q-Qo)/mA.h'] / 1000
dfForm['mode'] = dfForm['mode'].replace(3, 0)
dfForm.rename(columns = {'mode':'Step Type',
'time/s':'Run Time (h)',
'I/mA':'Current (A)',
'Ewe-Ece/V':'Potential vs. Counter (V)',
'Ewe/V':'Potential (V)',
'(Q-Qo)/mA.h':'Capacity (Ah)',
'Ns':'Step Number'},
inplace = True)
# Generate form file
if export_data:
pathFileForm = Path(path) / (cellname + ' Form.csv')
with open(pathFileForm, 'w') as f:
f.write(csvHeader)
print("Formation data exporting to:\n{}\n".format(str(pathFileForm)))
dfForm.to_csv(pathFileForm, mode = 'a', index = False)
# Concatenate
df = pd.concat([df, dfForm])
# Generate D dataframe if data available
if d_files:
dfD = pd.DataFrame({})
# Read, V average, and combine d file data
for file in d_files:
dFileLoc = Path(path) / file
with open(dFileLoc, 'r') as f:
# Read beginning of d file to discover lines in header
f.readline()
hlinenum = int(f.readline().strip().split()[-1]) - 1
# Read file into dataframe and convert to UHPC format
dfTempD = pd.read_csv(dFileLoc, skiprows = hlinenum, sep = '\t', encoding_errors = 'replace')
dfTempD = dfTempD[['mode', 'time/s', 'I/mA', 'Ewe-Ece/V', 'Ewe/V', '(Q-Qo)/mA.h', 'Ns', 'control/mA']]
# Convert 0A CC to NVX rest steps and trim off control I column
dfTempD['mode'].mask(dfTempD['control/mA'] == 0, 0, inplace = True)
dfTempD['mode'].mask(dfTempD['mode'] == 3, 0, inplace = True)
dfTempD.drop(columns = ['control/mA'], inplace = True)
dfTempDSteps = dfTempD.drop_duplicates(subset = ['Ns'], ignore_index = True)
# Detect if test ended prematurely
if dfTempDSteps['mode'].iloc[-1] != 0:
# Add dummy step at end to prevent overindexing
dummyD = dfTempD.loc[dfTempD.index[-1]:dfTempD.index[-1]].copy()
dummyD['Ns'] = dummyD['Ns'] + 1
dummyD['mode'] = 0
dfTempD = pd.concat([dfTempD, dummyD], ignore_index = True)
dfTempDSteps = pd.concat([dfTempDSteps, dummyD], ignore_index = True)
# Iterate over each pulse starting with their preceeding OCV V rest step
for i in dfTempDSteps.index:
if i != dfTempDSteps.index[-1]:
if dfTempDSteps['mode'][i] == 0 and dfTempDSteps['mode'][i+1] != 0:
# Average together all points of the rest step before a pulse into 1 point (OCV V)
ocvFinSel = dfTempD['Ns'] == dfTempDSteps['Ns'][i]
ocvFinVals = dfTempD[ocvFinSel].mean(axis = 0)
dfTempD[ocvFinSel] = ocvFinVals
# Determine nAvg, the number of datapoints to average together so that there are 10 points in the first step
nAvg = int(sum(dfTempD['Ns'] == dfTempDSteps['Ns'][i+1])/10)
# Iterate over each CC step in pulse
j = 1
while dfTempDSteps['mode'][i+j] != 0:
pulseInd = dfTempD[dfTempD['Ns'] == dfTempDSteps['Ns'][i+j]].index[0]
# Give OCV V to first point in pulse else remove first point in CC step
if j == 1:
dfTempD['Ewe-Ece/V'][pulseInd] = ocvFinVals['Ewe-Ece/V']
dfTempD['Ewe/V'][pulseInd] = ocvFinVals['Ewe/V']
else:
dfTempD.drop([pulseInd], inplace = True)
# Iterate over sets of nAvg datapoints within a CC step skipping the first and remainder datapoints
if pulseInd + nAvg <= dfTempD.index[-1]:
while dfTempD['Ns'][pulseInd + nAvg] == dfTempDSteps['Ns'][i+j]:
# Average together nAvg points into 1 point
CCPointVals = dfTempD.loc[pulseInd + 1:pulseInd + nAvg].mean(axis = 0)
dfTempD.loc[pulseInd + 1:pulseInd + nAvg] = CCPointVals.values
pulseInd = pulseInd + nAvg
if pulseInd + nAvg > dfTempD.index[-1]:
break
# Drop all remainder datapoints
nextStepInd = dfTempD[dfTempD['Ns'] == dfTempDSteps['Ns'][i+j+1]].index[0]
dfTempD.drop(dfTempD.loc[pulseInd + 1:nextStepInd - 1].index, inplace = True)
j = j + 1
else:
# Calculate OCV V for end of final pulse
if dfTempDSteps['mode'][i] == 0 and dfTempDSteps['mode'][i-1] == 0 and dfTempDSteps['mode'][i-2] == 0 and dfTempDSteps['mode'][i-3] == 1:
# Average together all points of the rest step before a pulse into 1 point (OCV V)
ocvFinSel = dfTempD['Ns'] == dfTempDSteps['Ns'][i]
ocvFinVals = dfTempD[ocvFinSel].mean(axis = 0)
dfTempD[ocvFinSel] = ocvFinVals
# Label steps after last OCV V as CC to prevent analysis (Test stopped prematurely)
else:
print(file, 'stopped mid pulse. Labelling last pulse as unfinished to prevent analysis.')
for i in range(len(dfTempDSteps.index)):
if dfTempDSteps['mode'].iat[-i-1] == 0:
dfTempDSteps['mode'].iat[-i-1] = 1
dfTempD['mode'][dfTempD['Ns'] == dfTempDSteps['Ns'].iat[-i-1]] = 1
else:
break
# Remove initial rest step series
for i in range(len(dfTempDSteps.index)):
if dfTempDSteps['mode'][i] == 0:
dfTempD.drop(dfTempD.loc[dfTempD['Ns'] == dfTempDSteps['Ns'][i]].index, inplace = True)
dfTempDSteps.drop(i, inplace = True)
else:
dfTempDSteps.reset_index(drop = True, inplace = True)
break
# Remove duplicates to simplify to one datapoint per averaging
dfTempD.drop_duplicates(inplace = True)
# Combine all rest steps except for the last step in a series into 1 step
for i in range(len(dfTempDSteps.index)):
if i != 0 and i != dfTempDSteps.index[-1]:
if dfTempDSteps['mode'][i] == 0 and dfTempDSteps['mode'][i-1] == 0 and dfTempDSteps['mode'][i+1] == 0:
dfTempD['Ns'][dfTempD['Ns'] == dfTempDSteps['Ns'][i]] = dfTempDSteps['Ns'][i-1]
dfTempDSteps['Ns'][i] = dfTempDSteps['Ns'][i-1]
# Combine all CC steps in a series
for i in range(len(dfTempDSteps.index)):
if i != 0:
if dfTempDSteps['mode'][i] != 0 and dfTempDSteps['mode'][i-1] != 0:
dfTempD['Ns'][dfTempD['Ns'] == dfTempDSteps['Ns'][i]] = dfTempDSteps['Ns'][i-1]
dfTempDSteps['Ns'][i] = dfTempDSteps['Ns'][i-1]
# Label last step as rest step if not already (Test stopped prematurely)
dfTempD['mode'].iloc[-1] = 0
dfTempDSteps['mode'].iloc[-1] = 0
# Relabel steps with continuous integers starting from 1
newDSteps = dfTempD.drop_duplicates(subset = ['Ns'], ignore_index = True)
dfTempD['Ns'].replace(newDSteps['Ns'].values, newDSteps.index+1, inplace = True)
dfTempDSteps['Ns'].replace(newDSteps['Ns'].values, newDSteps.index+1, inplace = True)
# Add last previous capacity, time, and step number to current data
if not(dfD.empty):
dfTempD['time/s'] = dfTempD['time/s'] + dfD['time/s'].iat[-1]
dfTempD['(Q-Qo)/mA.h'] = dfTempD['(Q-Qo)/mA.h'] + dfD['(Q-Qo)/mA.h'].iat[-1]
dfTempD['Ns'] = dfTempD['Ns'] + dfD['Ns'].iat[-1]
# Concatenate
dfD = pd.concat([dfD, dfTempD])
# Convert to hours, base units, and NVX labels while retaining order
dfD['time/s'] = dfD['time/s'] / 3600
dfD['I/mA'] = dfD['I/mA'] / 1000
dfD['(Q-Qo)/mA.h'] = dfD['(Q-Qo)/mA.h'] / 1000
dfD.rename(columns = {'mode':'Step Type',
'time/s':'Run Time (h)',
'I/mA':'Current (A)',
'Ewe-Ece/V':'Potential vs. Counter (V)',
'Ewe/V':'Potential (V)',
'(Q-Qo)/mA.h':'Capacity (Ah)',
'Ns':'Step Number'},
inplace = True)
# Add last capacity to output file
if not(df.empty):
dfD['Capacity (Ah)'] = dfD['Capacity (Ah)'] + df['Capacity (Ah)'].iat[-1]
# Generate D File
if export_data:
pathFileD = Path(path) / (cellname + ' Discharge.csv')
with open(pathFileD, 'w') as f:
f.write(csvHeader)
print("Discharge data exporting to:\n{}\n".format(str(pathFileD)))
dfD.to_csv(pathFileD, mode = 'a', index = False)
# Add last time, and step number to graphs
if not(df.empty):
dfD['Run Time (h)'] = dfD['Run Time (h)'] + df['Run Time (h)'].iat[-1]
dfD['Step Number'] = dfD['Step Number'] + df['Step Number'].iat[-1]
# Concatenate
df = pd.concat([df, dfD])
# Generate C dataframe if data available
if c_files:
dfC = pd.DataFrame({})
# Read, V average, and combine c file data
for file in c_files:
cFileLoc = Path(path) / file
with open(cFileLoc, 'r') as f:
# Read beginning of c file to discover lines in header
f.readline()
hlinenum = int(f.readline().strip().split()[-1]) - 1
# Read file into dataframe and convert to UHPC format
dfTempC = pd.read_csv(cFileLoc, skiprows = hlinenum, sep = '\t', encoding_errors = 'replace')
dfTempC = dfTempC[['mode', 'time/s', 'I/mA', 'Ewe-Ece/V', 'Ewe/V', '(Q-Qo)/mA.h', 'Ns', 'control/mA']]
# Convert 0A CC to NVX rest steps and trim off control I column
dfTempC['mode'].mask(dfTempC['control/mA'] == 0, 0, inplace = True)
dfTempC.drop(columns = ['control/mA'], inplace = True)
dfTempCSteps = dfTempC.drop_duplicates(subset = ['Ns'], ignore_index = True)
# Detect if test ended prematurely
if dfTempCSteps['mode'].iloc[-1] != 0:
# Add dummy step at end to prevent overindexing
dummyC = dfTempC.loc[dfTempC.index[-1]:dfTempC.index[-1]].copy()
dummyC['Ns'] = dummyC['Ns'] + 1
dummyC['mode'] = 0
dfTempC = pd.concat([dfTempC, dummyC], ignore_index = True)
dfTempCSteps = pd.concat([dfTempCSteps, dummyC], ignore_index = True)
# Iterate over each pulse starting with their preceeding OCV V rest step
for i in dfTempCSteps.index:
if i != dfTempCSteps.index[-1]:
if dfTempCSteps['mode'][i] == 0 and dfTempCSteps['mode'][i+1] != 0:
# Average together all points of the rest step before a pulse into 1 point (OCV V)
ocvFinSel = dfTempC['Ns'] == dfTempCSteps['Ns'][i]
ocvFinVals = dfTempC[ocvFinSel].mean(axis = 0)
dfTempC[ocvFinSel] = ocvFinVals
# Determine nAvg, the number of datapoints to average together so that there are 10 points in the first step
nAvg = int(sum(dfTempC['Ns'] == dfTempCSteps['Ns'][i+1])/10)
# Iterate over each CC step in pulse
j = 1
while dfTempCSteps['mode'][i+j] != 0:
pulseInd = dfTempC[dfTempC['Ns'] == dfTempCSteps['Ns'][i+j]].index[0]
# Give OCV V to first point in pulse else remove first point in CC step
if j == 1:
dfTempC['Ewe-Ece/V'][pulseInd] = ocvFinVals['Ewe-Ece/V']
dfTempC['Ewe/V'][pulseInd] = ocvFinVals['Ewe/V']
else:
dfTempC.drop([pulseInd], inplace = True)
# Iterate over sets of nAvg datapoints within a CC step skipping the first and remainder datapoints
if pulseInd + nAvg <= dfTempC.index[-1]:
while dfTempC['Ns'][pulseInd + nAvg] == dfTempCSteps['Ns'][i+j]:
# Average together nAvg points into 1 point
CCPointVals = dfTempC.loc[pulseInd + 1:pulseInd + nAvg].mean(axis = 0)
dfTempC.loc[pulseInd + 1:pulseInd + nAvg] = CCPointVals.values
pulseInd = pulseInd + nAvg
if pulseInd + nAvg > dfTempC.index[-1]:
break
# Drop all remainder datapoints
nextStepInd = dfTempC[dfTempC['Ns'] == dfTempCSteps['Ns'][i+j+1]].index[0]
dfTempC.drop(dfTempC.loc[pulseInd + 1:nextStepInd - 1].index, inplace = True)
j = j + 1
else:
# Calculate OCV V for end of final pulse
if dfTempCSteps['mode'][i] == 0 and dfTempCSteps['mode'][i-1] == 0 and dfTempCSteps['mode'][i-2] == 0 and dfTempCSteps['mode'][i-3] == 1:
# Average together all points of the rest step before a pulse into 1 point (OCV V)
ocvFinSel = dfTempC['Ns'] == dfTempCSteps['Ns'][i]
ocvFinVals = dfTempC[ocvFinSel].mean(axis = 0)
dfTempC[ocvFinSel] = ocvFinVals
# Label steps after last OCV V as CC to prevent analysis (Test stopped prematurely)
else:
print(file, 'ended prematurely. Labeling last pulse as unfinished to prevent analysis.')
for i in range(len(dfTempCSteps.index)):
if dfTempCSteps['mode'].iat[-i-1] == 0:
dfTempCSteps['mode'].iat[-i-1] = 1
dfTempC['mode'][dfTempC['Ns'] == dfTempCSteps['Ns'].iat[-i-1]] = 1
else:
break
# Remove initial rest step series
for i in range(len(dfTempCSteps.index)):
if dfTempCSteps['mode'][i] == 0:
dfTempC.drop(dfTempC.loc[dfTempC['Ns'] == dfTempCSteps['Ns'][i]].index, inplace = True)
dfTempCSteps.drop(i, inplace = True)
else:
dfTempCSteps.reset_index(drop = True, inplace = True)
break
# Remove duplicates to simplify to one datapoint per averaging
dfTempC.drop_duplicates(inplace = True)
# Combine all rest steps in a series except for the last step into 1 step
for i in range(len(dfTempCSteps.index)):
if i != 0 and i != dfTempCSteps.index[-1]:
if dfTempCSteps['mode'][i] == 0 and dfTempCSteps['mode'][i-1] == 0 and dfTempCSteps['mode'][i+1] == 0:
dfTempC['Ns'][dfTempC['Ns'] == dfTempCSteps['Ns'][i]] = dfTempCSteps['Ns'][i-1]
dfTempCSteps['Ns'][i] = dfTempCSteps['Ns'][i-1]
# Combine all CC steps in a series
for i in range(len(dfTempCSteps.index)):
if i != 0:
if dfTempCSteps['mode'][i] != 0 and dfTempCSteps['mode'][i-1] != 0:
dfTempC['Ns'][dfTempC['Ns'] == dfTempCSteps['Ns'][i]] = dfTempCSteps['Ns'][i-1]
dfTempCSteps['Ns'][i] = dfTempCSteps['Ns'][i-1]
# Label last step as rest step if not already (Test stopped prematurely)
dfTempC['mode'].iloc[-1] = 0
dfTempCSteps['mode'].iloc[-1] = 0
# Relabel steps with continuous integers starting from 1
newCSteps = dfTempC.drop_duplicates(subset = ['Ns'], ignore_index = True)
dfTempC['Ns'].replace(newCSteps['Ns'].values, newCSteps.index+1, inplace = True)
dfTempCSteps['Ns'].replace(newCSteps['Ns'].values, newCSteps.index+1, inplace = True)
# Add last previous capacity, time, and step number to current data
if not(dfC.empty):
dfTempC['time/s'] = dfTempC['time/s'] + dfC['time/s'].iat[-1]
dfTempC['(Q-Qo)/mA.h'] = dfTempC['(Q-Qo)/mA.h'] + dfC['(Q-Qo)/mA.h'].iat[-1]
dfTempC['Ns'] = dfTempC['Ns'] + dfC['Ns'].iat[-1]
# Concatenate
dfC = pd.concat([dfC, dfTempC])
# Convert to hours, base units, and NVX labels while retaining order
dfC['time/s'] = dfC['time/s'] / 3600
dfC['I/mA'] = dfC['I/mA'] / 1000
dfC['(Q-Qo)/mA.h'] = dfC['(Q-Qo)/mA.h'] / 1000
dfC.rename(columns = {'mode':'Step Type',
'time/s':'Run Time (h)',
'I/mA':'Current (A)',
'Ewe-Ece/V':'Potential vs. Counter (V)',
'Ewe/V':'Potential (V)',
'(Q-Qo)/mA.h':'Capacity (Ah)',
'Ns':'Step Number'},
inplace = True)
# Add last capacity to output file
if not(df.empty):
dfC['Capacity (Ah)'] = dfC['Capacity (Ah)'] + df['Capacity (Ah)'].iat[-1]
# Generate C file
if export_data:
pathFileC = Path(path) / (cellname + ' Charge.csv')
with open(pathFileC, 'w') as f:
f.write(csvHeader)
print("Charge data exporting to:\n{}\n".format(str(pathFileC)))
dfC.to_csv(pathFileC, mode = 'a', index = False)
# Add last time, and step number to graphs
if not(df.empty):
dfC['Run Time (h)'] = dfC['Run Time (h)'] + df['Run Time (h)'].iat[-1]
dfC['Step Number'] = dfC['Step Number'] + df['Step Number'].iat[-1]
# Concatenate
df = pd.concat([df, dfC])
# Generate full file
if export_data:
pathFile = Path(path) / (cellname + ' All.csv')
with open(pathFile, 'w') as f:
f.write(csvHeader)
df.to_csv(pathFile, mode = 'a', index = False)
# Generate complete graph
fig, axs = plt.subplots(nrows = 1, ncols = 2, sharey = True, figsize = (6, 3), gridspec_kw = {'wspace':0.0})
if form_files:
axs[0].plot(dfForm['Run Time (h)'], dfForm['Potential vs. Counter (V)'], 'k--', label = 'Formation vs. $E_c$')
axs[0].plot(dfForm['Run Time (h)'], dfForm['Potential (V)'], 'k-', label = 'Formation vs. $E_r$')
if d_files:
axs[0].plot(dfD['Run Time (h)'], dfD['Potential vs. Counter (V)'], 'r--', label = 'Discharge vs. $E_c$')
axs[0].plot(dfD['Run Time (h)'], dfD['Potential (V)'], 'r-', label = 'Discharge vs. $E_r$')
if c_files:
axs[0].plot(dfC['Run Time (h)'], dfC['Potential vs. Counter (V)'], 'b--', label = 'Charge vs. $E_c$')
axs[0].plot(dfC['Run Time (h)'], dfC['Potential (V)'], 'b-', label = 'Charge vs. $E_r$')
axs[0].set_xlabel('Time (h)')
axs[0].set_ylabel('Voltage (V)')
axs[0].xaxis.set_minor_locator(ticker.AutoMinorLocator())
axs[0].yaxis.set_minor_locator(ticker.AutoMinorLocator())
axs[0].grid(which = 'minor', color = 'lightgrey')
if form_files:
axs[1].plot(dfForm['Capacity (Ah)']*1000000/massVal, dfForm['Potential vs. Counter (V)'], 'k--', label = 'Formation vs. $E_c$')
axs[1].plot(dfForm['Capacity (Ah)']*1000000/massVal, dfForm['Potential (V)'], 'k-', label = 'Formation vs. $E_r$')
if d_files:
axs[1].plot(dfD['Capacity (Ah)']*1000000/massVal, dfD['Potential vs. Counter (V)'], 'r--', label = 'Discharge vs. $E_c$')
axs[1].plot(dfD['Capacity (Ah)']*1000000/massVal, dfD['Potential (V)'], 'r-', label = 'Discharge vs. $E_r$')
if c_files:
axs[1].plot(dfC['Capacity (Ah)']*1000000/massVal, dfC['Potential vs. Counter (V)'], 'b--', label = 'Charge vs. $E_c$')
axs[1].plot(dfC['Capacity (Ah)']*1000000/massVal, dfC['Potential (V)'], 'b-', label = 'Charge vs. $E_r$')
axs[1].set_xlabel('Specific Capacity\n(mAh g$\mathregular{^{-1}}$)')
axs[1].xaxis.set_minor_locator(ticker.AutoMinorLocator())
axs[1].yaxis.set_minor_locator(ticker.AutoMinorLocator())
axs[1].grid(which = 'minor', color = 'lightgrey')
plt.legend(bbox_to_anchor = (1.0, 0.5), loc = 'center left')
if export_fig:
figname = Path(path) / '{} Protocol.jpg'.format(cellname)
print(figname)
plt.savefig(figname, bbox_inches = 'tight')
plt.show()
plt.close()
print("")
if d_files and c_files:
dfDOCV = dfD[dfD['Step Type'] != 0].drop_duplicates(['Step Number'])
dfCOCV = dfC[dfC['Step Type'] != 0].drop_duplicates(['Step Number'])
fig, axs = plt.subplots(nrows = 1, ncols = 1, figsize = (6, 3), gridspec_kw = {'wspace':0.0})
axs.plot(dfDOCV['Capacity (Ah)']*1000000/massVal, dfDOCV['Potential (V)'], 'r.-', label = 'Discharge Relaxed vs. $E_r$')
axs.plot(dfCOCV['Capacity (Ah)']*1000000/massVal, dfCOCV['Potential (V)'], 'b.-', label = 'Charge Relaxed vs. $E_r$')
axs.set_xlabel('Specific Capacity\n(mAh g$\mathregular{^{-1}}$)')
axs.set_ylabel('Voltage (V)')
axs.xaxis.set_minor_locator(ticker.AutoMinorLocator())
axs.yaxis.set_minor_locator(ticker.AutoMinorLocator())
axs.grid(which = 'minor', color = 'lightgrey')
plt.legend(frameon = True)
if export_fig:
figname = Path(path) / '{} Relax Match.jpg'.format(cellname)
print(figname)
plt.savefig(figname, bbox_inches = 'tight')
plt.show()
plt.close()
print("")
class AMIDR():
def __init__(self, path, uhpc_file, single_pulse, export_data = True, export_fig = None, use_input_cap = True,
capacitance_corr = False, fcap_min = 0.0, spliced = False, force2e = False, parselabel = None):
print("_________________________________")
if not(export_fig is None): ('There is no figure to export. Feel free to neglect this argument.')
self.single_p = single_pulse
self.capacitance_corr = capacitance_corr
self.fcap_min = fcap_min
if parselabel is None:
self.cell_label = ('.').join(uhpc_file.split('.')[0:-1])
else:
self.cell_label = ('.').join(uhpc_file.split('.')[0:-1]) + '-' + parselabel
print(self.cell_label + "\n")
self.dst = Path(path) / self.cell_label
# If does not exist, create dir.
if self.dst.is_dir() is False and export_data is True:
self.dst.mkdir()
print("Create directory: {}".format(self.dst))
self.src = Path(path)
self.uhpc_file = self.src / uhpc_file
with open(self.uhpc_file, 'r') as f:
lines = f.readlines()
nlines = len(lines)
headlines = []
for i in range(nlines):
headlines.append(lines[i])
l = lines[i].strip().split()
if l[0][:6] == '[Data]':
nskip = i+1
break
header = ''.join(headlines)
del lines
# find mass and theoretical cap using re on header str
m = re.search('Mass\s+\(.*\):\s+(\d+)?\.\d+', header)
m = m.group(0).split()
mass_units = m[1][1:-2]
if mass_units == 'mg':
self.mass = float(m[-1]) / 1000
else:
self.mass = float(m[-1])
m = re.search('Capacity\s+(.*):\s+(\d+)?\.\d+', header)
m = m.group(0).split()
cap_units = m[1][1:-2]
if cap_units == 'mAHr':
self.input_cap = float(m[-1]) / 1000
else:
self.input_cap = float(m[-1])
m = re.search('Cell: .+?(?=,|\\n)', header)
m = m.group(0).split()
self.cellname = ' '.join(m[1:])
#self.cellname = headlines[1][-1]
#self.mass = float(headlines[4][-1]) / 1000
#self.input_cap = float(headlines[5][-1]) / 1000 # Convert to Ah
#if headlines[10][0] == '[Data]':
# hlinenum = 11
#hline = f.readline()
# hline = headlines[10]
#else:
# hlinenum = 12
#f.readline()
#hline = f.readline()
# hline = headlines[11]
print("Working on cell: {}".format(self.cellname))
print("Positive electrode active mass: {} g".format(self.mass))
print("Input cell capacity: {} Ah\n".format(round(self.input_cap, 10)))
self.df = pd.read_csv(self.uhpc_file, header = nskip)
self.df.rename(columns = {'Capacity (Ah)': 'Capacity',
'Potential (V)': 'Potential',
'Potential vs. Counter (V)':'Label Potential',
'Run Time (h)': 'Time',
'Time (h)': 'Time',
'Current (A)': 'Current',
'Cycle Number': 'Cycle',
'Meas I (A)': 'Current',
'Step Type': 'Step',
'Prot.Step': 'Prot_step',
'Step Number': 'Prot_step'},
inplace = True)
if single_pulse == True and spliced == True:
print("single_pulse cannot operate on spliced files. Manually clean up your spliced file and select spliced = false\n")
# Add Prot_step column if column does not yet exist or spliced file is used.
if 'Prot_step' not in self.df.columns or spliced == True:
s = self.df.Step
self.df['Prot_step'] = s.ne(s.shift()).cumsum() - 1
# Adjust data where time is not monotonically increasing.
t = self.df['Time'].values
cap = self.df['Capacity'].values
dt = t[1:] - t[:-1]
indst = np.where(dt < 0.0)[0]
if len(indst) > 0:
print("Indices being adjusted due to time non-monotonicity: {}".format(indst))
self.df['Time'][indst+1] = (t[indst] + t[indst+2])/2
self.df['Capacity'][indst+1] = (cap[indst] + cap[indst+2])/2
# Adjust data where potential is negative.
indsn = self.df.index[self.df['Potential'] < 0.0].tolist()
if len(indsn) > 0:
print("Indices being adjusted due to negative voltage: {}".format(indsn))
self.df['Potential'][indsn] = (t[indsn-1] + t[indsn+1])/2
if len(indst) > 0 or len(indsn) > 0: print("\n")
if 'Label Potential' not in self.df:
self.df['Label Potential'] = self.df['Potential'].copy()
elif force2e:
self.df['Potential'] = self.df['Label Potential'].copy()
print("3-electrode data detected. Ignoring working potential and using complete cell potential for everything. [NOT RECCOMMENDED]\n")
else:
print("3-electrode data detected. Using working potential for calculations and complete cell potential for labelling.\n")
self.sigdf = self._find_sigcurves()
self.sc_stepnums = self.sigdf['Prot_step'].unique()
self.capacity = self.sigdf['Capacity'].max() - self.sigdf['Capacity'].min()
self.spec_cap = self.capacity / self.mass
if use_input_cap:
self.capacity = self.input_cap
else:
print("Specific Capacity achieved by signature curves: {0:.2f} mAh/g".format(self.spec_cap*1000))
print("Using {:.8f} Ah to compute rates.\n".format(self.capacity))
self.caps, self.cumcaps, self.volts, self.fcaps, self.rates, self.eff_rates, self.currs, \
self.ir, self.dqdv, self.resistdrop, self.icaps, self.avg_caps, self.ivolts, self.cvolts, \
self.avg_volts, self.dvolts, self.vlabels = self._parse_sigcurves()
self.nvolts = len(self.caps)
if export_data:
caprate_fname = self.dst / '{0} Parsed.xlsx'.format(self.cell_label)
writer = pd.ExcelWriter(caprate_fname)
for i in range(self.nvolts):
if self.single_p is False:
caprate_df = pd.DataFrame(data = {'Specific Capacity': self.cumcaps[i],
'Fractional Capacity': self.fcaps[i],
'Effective C/n Rate': self.eff_rates[i],
'C/n Rate': self.rates[i]})
else:
caprate_df = pd.DataFrame(data = {'Specific Capacity': self.caps[i],
'Voltage': self.volts[i],
'Fractional Capacity': self.fcaps[i],
'qi/I': self.eff_rates[i]})
caprate_df.to_excel(writer, sheet_name = self.vlabels[i], index = False)
print("Parsed data exporting to:\n{0}\n".format(str(caprate_fname)))
writer.save()
writer.close()
def _find_sigcurves(self):
# Use control "step" to find sequence of charge/discharge - OCV characteristic of signature curves.
newdf = self.df.drop_duplicates(subset = ['Step', 'Prot_step'])
steps = newdf['Step'].values
prosteps = newdf['Prot_step'].values
ocv_inds = np.where(steps == 0)[0]
if self.single_p is False:
# Require a min of 3 OCV steps with the same step before and after
# to qualify as a signature curve.
for i in range(len(ocv_inds)):
if steps[ocv_inds[i] - 1] == steps[ocv_inds[i+2] + 1]:
first_sig_step = prosteps[ocv_inds[i] - 1]
break
for i in range(len(ocv_inds)):
ind = -i - 1
if steps[ocv_inds[ind] + 1] != steps[ocv_inds[ind] - 1]:
last_sig_step = prosteps[ocv_inds[ind] - 1]
break
elif steps[ocv_inds[ind] + 1] != steps[ocv_inds[ind] + 2]:
last_sig_step = prosteps[ocv_inds[ind] + 1]
break
if i == len(ocv_inds) - 1:
last_sig_step = prosteps[ocv_inds[-1] + 1]
else:
#single_pulse sigcurves selection
for i in range(len(ocv_inds)):
if i+1 == len(ocv_inds):
print("No adjacent OCV steps detected. Protocol is likely not single_pulse.")
break
if ocv_inds[i] == ocv_inds[i+1] - 1:
first_sig_step = prosteps[ocv_inds[i] - 1]
break
for i in range(len(ocv_inds)):
if ocv_inds[-i] == ocv_inds[-i-1] + 1:
last_sig_step = prosteps[ocv_inds[-i]]
break
print("Signature curve steps: {0} - {1}".format(first_sig_step, last_sig_step))
sigdf = self.df.loc[(self.df['Prot_step'] >= first_sig_step) & (self.df['Prot_step'] <= last_sig_step)]
return sigdf
def _parse_sigcurves(self):
sigs = self.sigdf.loc[self.sigdf['Step'] != 0]
Vstart = np.around(sigs['Label Potential'].values[0], decimals = 3)
Vend = np.around(sigs['Label Potential'].values[-1], decimals = 3)
print("Voltages: {:.3f} V - {:.3f} V".format(Vstart, Vend))
sigsteps = sigs['Prot_step'].unique()
nsig = len(sigsteps)
print("Found {} pulse steps in signature curves.\n".format(nsig))
caps = []
cumcaps = []
volts = []
fcaps = []
rates = []
initcap = []
cutcap = []
initvolts = []
cutvolts = []
currs = []
ir = []
dqdv = []
resistdrop = []
eff_rates = []
if self.single_p is False:
for i in range(nsig):
step = sigs.loc[sigs['Prot_step'] == sigsteps[i]]
pulsecaps = step['Capacity'].values
pulsevolts = step['Potential'].values
currents = np.absolute(step['Current'].values)
rate = self.capacity / np.average(currents)
minarg = np.argmin(np.absolute(RATES - rate))
# slice first and last current values if possible.
# if less than 4(NVX) or 5(UHPC) data points, immediate voltage cutoff reached, omit step.
if len(currents) > 3:
if pulsevolts[-2] == np.around(pulsevolts[-2], decimals = 2):
currents = currents[1:-1]
cvoltind = -2
elif len(currents) > 4:
if pulsevolts[-3] == np.around(pulsevolts[-3], decimals = 2):
currents = currents[1:-1]
cvoltind = -3
else:
continue
else:
continue
else:
continue
# determine dqdv based on the measurements before the voltage cutoff
diffq = (pulsecaps[cvoltind-2] - pulsecaps[cvoltind-1]) / (pulsevolts[cvoltind-2] - pulsevolts[cvoltind-1])
if caps == []:
caps.append([np.amax(pulsecaps) - np.amin(pulsecaps)])
volts.append([np.amax(pulsevolts) - np.amin(pulsevolts)])
rates.append([RATES[minarg]])
initcap.append([pulsecaps[0]])
cutcap.append([pulsecaps[cvoltind]])
initvolts.append([pulsevolts[0]])
cutvolts.append([pulsevolts[cvoltind]])
currs.append([np.average(currents)])
ir.append([np.absolute(pulsevolts[0] - pulsevolts[1])])
dqdv.append([diffq])
resistdrop.append([ir[-1][-1]/currs[-1][-1]])
else:
if pulsevolts[cvoltind] == cutvolts[-1][-1]:
caps[-1].append(np.amax(pulsecaps) - np.amin(pulsecaps))
volts[-1].append(np.amax(pulsevolts) - np.amin(pulsevolts))
rates[-1].append(RATES[minarg])
cutcap[-1].append(pulsecaps[cvoltind])
cutvolts[-1].append(pulsevolts[cvoltind])
currs[-1].append(np.average(currents))
ir[-1].append(np.absolute(pulsevolts[0] - pulsevolts[1]))
dqdv[-1].append(diffq)
resistdrop[-1].append(ir[-1][-1]/currs[-1][-1])
else:
if np.absolute(pulsevolts[-2] - cutvolts[-1][-1]) < 0.001:
continue
caps.append([np.amax(pulsecaps) - np.amin(pulsecaps)])
volts.append([np.amax(pulsevolts) - np.amin(pulsevolts)])
rates.append([RATES[minarg]])
initcap.append([pulsecaps[0]])
cutcap.append([pulsecaps[cvoltind]])
initvolts.append([pulsevolts[0]])
cutvolts.append([pulsevolts[cvoltind]])
currs.append([np.average(currents)])
ir.append([np.absolute(pulsevolts[0] - pulsevolts[1])])
dqdv.append([diffq])
resistdrop.append([ir[-1][-1]/currs[-1][-1]])
nvolts = len(caps)
for i in range(nvolts):
fcaps.append(np.cumsum(caps[i]) / np.sum(caps[i]))
cumcaps.append(np.cumsum(caps[i]))
eff_rates.append(cumcaps[i][-1]/currs[i])
# Remove data where capacity is too small due to IR
# i.e., voltage cutoff was reached immediately.
inds = np.where(fcaps[i] < self.fcap_min)[0]
if len(inds) > 0:
print("{0} Pulse(s) to {1} removed due to being below fcap min.\n".format(eff_rates[i][inds], cutvolts[i][inds]))
caps[i] = np.delete(caps[i], inds)
volts[i] = np.delete(volts[i], inds)
cumcaps[i] = np.delete(cumcaps[i], inds)
fcaps[i] = np.delete(fcaps[i], inds)
eff_rates[i] = np.delete(eff_rates[i], inds)
rates[i] = np.delete(rates[i], inds)
cutcap[i] = np.delete(cutcap[i], inds)
cutvolts[i] = np.delete(cutvolts[i], inds)
currs[i] = np.delete(currs[i], inds)
ir[i] = np.delete(ir[i], inds)
dqdv[i] = np.delete(dqdv[i], inds)
resistdrop[i] = np.delete(resistdrop[i], inds)
if self.capacitance_corr == True:
print("Capacitance correction cannot be applied to multi-pulse AMID data. Data is being analyzed without capacitance correction.\n")
else:
# idcaps is the idealized capacity for a given voltage based upon dqdv
# cumcurrs is the cumulative averge current for determining where C should be calculated
idcaps = []
cumcurrs = []
voltsAct = []
time = []
for i in range(nsig):
step = sigs.loc[sigs['Prot_step'] == sigsteps[i]]
pulsecaps = step['Capacity'].values
pulsevolts = step['Potential'].values
lpulsevolts = step['Label Potential'].values
currents = np.absolute(step['Current'].values)
runtime = step['Time'].values
# Collect succeeding OCV steps (1 OCV or 2 OCV) to calculate dqdv
ocvstep = self.sigdf.loc[self.sigdf['Prot_step'] == sigsteps[i] + 2]
if ocvstep['Step'].values[0] != 0:
ocvstep = self.sigdf.loc[self.sigdf['Prot_step'] == sigsteps[i] + 1]
ocvpulsecaps = ocvstep['Capacity'].values
ocvvolts = ocvstep['Potential'].values
ocvlvolts = ocvstep['Label Potential'].values
if len(pulsevolts) > 1:
ir.append([np.absolute(pulsevolts[1] - pulsevolts[0])])
else:
ir.append([np.nan])
initcap.append([pulsecaps[0]])
cutcap.append([ocvpulsecaps[-1]])
initvolts.append([lpulsevolts[0]])
cutvolts.append([ocvlvolts[-1]])
dqdv.append([(pulsecaps[0] - ocvpulsecaps[-1])/(pulsevolts[0] - ocvvolts[-1])])
time.append(np.absolute(runtime[1:] - runtime[0]))
caps.append(np.absolute(pulsecaps[1:] - pulsecaps[0]))
cumcaps.append(np.absolute(pulsecaps[1:] - pulsecaps[0]))
volts.append(np.absolute(pulsevolts[1:] - pulsevolts[0]))
idcaps.append(np.absolute(dqdv[-1][0]*(pulsevolts[1:] - pulsevolts[0])))
currs.append(currents[1:])
voltsAct.append(pulsevolts[1:])
cumcurrs.append([])
rates.append([])
for j in range(len(currents[1:])):
cumcurrs[-1].append(np.average(currents[1:j+2]))
minarg = np.argmin(np.absolute(RATES - self.capacity / cumcurrs[-1][j]))
rates[-1].append(RATES[minarg])
if len(pulsevolts) > 1:
resistdrop.append([ir[-1][0]/currs[-1][0]])
else:
resistdrop.append([np.nan])
nvolts = len(caps)
if self.capacitance_corr == True:
#DL capacitance is calculated from the first 5 consistent current datapoints in the lowest V pulse.
lowVind = cutvolts.index(min(cutvolts))
A = np.ones((8, 2))
y = np.zeros(8)
n = 0
for i in range(len(currs[lowVind])):
if n == 8:
break
if abs(currs[lowVind][i]/currs[lowVind][i+1] - 1) < 0.01:
A[n][0] = voltsAct[lowVind][i+1]
y[n] = caps[lowVind][i+1]
n = n + 1
else:
A = np.ones((8, 2))
y = np.zeros(8)
n = 0
capacitance = abs(np.linalg.lstsq(A, y)[0][0])
print("Double layer capacitance found at lowest V pulse: {:.2f} nF".format(1.0e9*capacitance))
rohm = np.power(10, stats.mode(np.round(np.log10(resistdrop), 2))[0])[0][0]
print("Logarithmic mode of ohmic resistance over all pulses: {:.2f} Ω\n".format(rohm))
for i in range(nvolts):
dlcaps = []
for j in range(len(voltsAct[i])):
if voltsAct[i][0] > voltsAct[i][-1]:
if voltsAct[i][0] + ir[i][0] - currs[i][j]*rohm > voltsAct[i][j]:
dlcaps.append(capacitance*((voltsAct[i][0] + ir[i][0] - currs[i][j]*rohm) - voltsAct[i][j]))
else:
dlcaps.append(0)
else:
if voltsAct[i][0] - ir[i][0] + currs[i][j]*rohm < voltsAct[i][j]:
dlcaps.append(capacitance*(voltsAct[i][j] - (voltsAct[i][0] - ir[i][0] + currs[i][j]*rohm)))
else:
dlcaps.append(0)