forked from Samuel-Buteau/universal-battery-database
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneware_processing_functions.py
1876 lines (1585 loc) · 68.1 KB
/
neware_processing_functions.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
from cycling.models import *
import os
from django.utils import timezone
import collections
import datetime
import os.path
from itertools import repeat
from itertools import starmap
from django.db.models import Max, Q, F
import re
import pytz
from django.db import transaction
from scipy.interpolate import PchipInterpolator
import math
from background_task import background
from scipy import special
import numpy as np
halifax_timezone = pytz.timezone("America/Halifax")
import filename_database.models as filename_models
def get_good_neware_files():
exp_type = filename_models.ExperimentType.objects.get(
category = filename_models.Category.objects.get(name = "cycling"),
subcategory = filename_models.SubCategory.objects.get(name = "neware"),
)
return filename_models.DatabaseFile.objects.filter(
is_valid = True, deprecated = False,
).exclude(
valid_metadata = None
).filter(valid_metadata__experiment_type = exp_type)
def get_cell_ids():
exp_type = filename_models.ExperimentType.objects.get(
category = filename_models.Category.objects.get(name = "cycling"),
subcategory = filename_models.SubCategory.objects.get(name = "neware"),
)
all_current_cell_ids = filename_models.DatabaseFile.objects.filter(
is_valid = True, deprecated = False,
).exclude(
valid_metadata = None
).filter(
valid_metadata__experiment_type = exp_type
).values_list(
"valid_metadata__cell_id", flat = True,
).distinct()
return all_current_cell_ids
def strip(string, sub):
if string.endswith(sub):
return strip(string[:-1], sub)
else:
return string
def parse_time(my_realtime_string):
matchObj1 = re.match(
r"(\d\d\d\d)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})",
my_realtime_string,
)
matchObj2 = re.match(
r"(\d{1,2})/(\d{1,2})/(\d\d\d\d) (\d{1,2}):(\d{1,2}):(\d{1,2})",
my_realtime_string,
)
matchObj3 = re.match(
r"(\d{1,2})/(\d{1,2})/(\d\d\d\d) (\d{1,2}):(\d{1,2})",
my_realtime_string,
)
second_accuracy = True
if matchObj1:
int_year = int(matchObj1.group(1))
int_month = int(matchObj1.group(2))
int_day = int(matchObj1.group(3))
int_hour = int(matchObj1.group(4))
int_minute = int(matchObj1.group(5))
int_second = int(matchObj1.group(6))
elif matchObj2:
int_month = int(matchObj2.group(1))
int_day = int(matchObj2.group(2))
int_year = int(matchObj2.group(3))
int_hour = int(matchObj2.group(4))
int_minute = int(matchObj2.group(5))
int_second = int(matchObj2.group(6))
elif matchObj3:
int_month = int(matchObj3.group(1))
int_day = int(matchObj3.group(2))
int_year = int(matchObj3.group(3))
int_hour = int(matchObj3.group(4))
int_minute = int(matchObj3.group(5))
int_second = 0
second_accuracy = False
else:
raise Exception(
"tried to parse time {}, but only known formats are YYYY-MM-DD hh:mm:ss, MM/DD/YYYY hh:mm:ss, MM/DD/YYYY hh:mm".format(
my_realtime_string
)
)
return datetime.datetime(
int_year, int_month, int_day,
hour = int_hour, minute = int_minute, second = int_second,
), second_accuracy
def identify_variable_position(separated, label, this_line):
if label not in separated:
raise Exception("This format is unknown! {}".format(this_line))
return separated.index(label)
def test_occupied_position(separated, pos):
if len(separated) <= pos:
return False
elif separated[pos]:
return True
else:
return False
def read_neware(
path, last_imported_cycle = -1, capacity_units = 1.0,
voltage_units = 1.0 / 1000.0, current_units = 1.0,
):
print("\tREADING FILE AS NEWARE FORMAT. {}".format(path))
"""
TEMPDOC:
this is a fairly general function to process a neware file no matter which format it has been saved in.
First, determine which format it is.
Open the file, see if it is nested or separated.
Then,
if nested, parse the headers, then compile the data.
else, go to Step data, parse that header, then compile all step data.
then, go to Record data, parse that header, then compile all record data.
"""
with open(path, "r", errors = "ignore") as my_file:
this_line = my_file.readline()
separated = this_line.split("\n")[0].split("\t")
if len(separated) == 1:
nested = False
# print("NOT nested", separated)
elif separated[0]:
nested = True
# print("nested", separated)
else:
raise Exception("This format is unknown. {}".format(this_line))
with open(path, "r", errors = "ignore") as my_file:
def get_header_line():
this_line = my_file.readline()
separated = [strip(h.split("(")[0], " ")
for h in this_line.split("\n")[0].split("\t")]
stripped = [h for h in separated if h]
return this_line, separated, stripped
def get_normal_line():
this_line = my_file.readline()
separated = this_line.split("\n")[0].split("\t")
stripped = [s for s in separated if s]
return this_line, separated, stripped
def parse_step_header(position, nested = True):
# nested
this_line, separated, stripped = get_header_line()
# Verify that this is the step header
if nested and separated[0]:
raise Exception("This format is unknown! {}".format(this_line))
if not nested:
position["cycle_id"] = identify_variable_position(
separated, label = "Cycle ID", this_line = this_line,
)
position["step_id"] = identify_variable_position(
separated, label = "Step ID", this_line = this_line,
)
if "Step Name" in separated:
position["step_type"] = identify_variable_position(
stripped, label = "Step Name", this_line = this_line,
)
elif "Step Type" in separated:
position["step_type"] = identify_variable_position(
stripped, label = "Step Type", this_line = this_line,
)
else:
raise Exception("This format is unknown! {}".format(this_line))
def parse_record_header(position, nested = True):
this_line, separated, stripped = get_header_line()
# Verify that this is the record header
if nested and (separated[0] or separated[position["step_id"]]):
raise Exception("This format is unknown! {}".format(this_line))
if not nested:
position["cycle_id"] = identify_variable_position(
separated, label = "Cycle ID", this_line = this_line,
)
position["step_id"] = identify_variable_position(
separated, label = "Step ID", this_line = this_line,
)
position["record_id"] = identify_variable_position(
separated, label = "Record ID", this_line = this_line,
)
if "Vol" in stripped:
iter_dat = [
("voltage", "Vol"),
("current", "Cur"),
("capacity", "Cap"),
("time", "Time"),
("realtime", "Realtime"),
]
elif "Voltage" in stripped:
iter_dat = [
("voltage", "Voltage"),
("current", "Current"),
("capacity", "Capacity"),
("time", "Time"),
("realtime", "Realtime"),
]
for id, s in iter_dat:
position[id] = identify_variable_position(
stripped,
label = s, this_line = this_line,
)
def parse_normal_step(
position, current_cycle, current_step,
imported_data, separated, stripped, nested,
):
if nested:
current_step = int(separated[position["step_id"]])
else:
if test_occupied_position(separated, position["cycle_id"]):
current_cycle = int(separated[position["cycle_id"]])
else:
return current_cycle, current_step
if (not nested) and (current_cycle <= last_imported_cycle):
return current_cycle, current_step
if test_occupied_position(separated, position["step_id"]):
current_step = int(separated[position["step_id"]])
else:
return current_cycle, current_step
if not current_cycle in imported_data.keys():
imported_data[current_cycle] = collections.OrderedDict([])
if test_occupied_position(stripped, position["step_type"]):
step_type = stripped[position["step_type"]]
imported_data[current_cycle][current_step] = (step_type, [])
else:
return current_cycle, current_step
return current_cycle, current_step
def parse_normal_record(
position, current_cycle, current_step,
imported_data, separated, stripped, nested,
):
if not nested:
if test_occupied_position(separated, position["cycle_id"]):
current_cycle = int(separated[position["cycle_id"]])
else:
return
if current_cycle <= last_imported_cycle:
return
if test_occupied_position(separated, position["step_id"]):
current_step = int(separated[position["step_id"]])
else:
return
my_extracted_strings = {}
for i in ["realtime", "capacity", "current", "voltage"]:
if test_occupied_position(stripped, position[i]):
my_extracted_strings[i] = stripped[position[i]]
else:
continue
my_cap_float = capacity_units * float(
my_extracted_strings["capacity"])
my_cur_float = current_units * float(
my_extracted_strings["current"])
my_vol_float = voltage_units * float(
my_extracted_strings["voltage"])
my_time, second_accuracy = parse_time(
my_extracted_strings["realtime"])
imported_data[current_cycle][current_step][1].append([
my_vol_float, my_cur_float, my_cap_float, my_time,
second_accuracy,
])
current_cycle = -1
current_step = -1
imported_data = collections.OrderedDict([])
position = {}
if nested:
# Cycle
this_line, separated, stripped = get_header_line()
position["cycle_id"] = identify_variable_position(
separated, label = "Cycle ID", this_line = this_line,
)
# Step
parse_step_header(position, nested = nested)
# Record
parse_record_header(position, nested = nested)
for i in range(1000000000):
this_line, separated, stripped = get_normal_line()
if this_line == "":
break
if test_occupied_position(separated, position["cycle_id"]):
current_cycle = int(separated[position["cycle_id"]])
if current_cycle <= last_imported_cycle:
continue
imported_data[current_cycle] = collections.OrderedDict([])
if (current_cycle % 100) == 0:
print("\t\tREAD CYCLES UP TO {}".format(current_cycle))
else:
if current_cycle <= last_imported_cycle:
continue
if test_occupied_position(separated, position["step_id"]):
current_cycle, current_step = parse_normal_step(
position, current_cycle, current_step,
imported_data, separated, stripped, nested,
)
elif test_occupied_position(separated,
position["record_id"]):
parse_normal_record(
position, current_cycle, current_step,
imported_data, separated, stripped, nested,
)
else:
continue
else:
# not nested
for i in range(10000000000):
this_line, separated, stripped = get_normal_line()
if separated[0] == "Step Data":
break
# This is the step data header
parse_step_header(position, nested = nested)
# This is the step data
for i in range(10000000000):
this_line, separated, stripped = get_normal_line()
if separated[0] == "Record Data":
break
current_cycle, current_step = parse_normal_step(
position, current_cycle, current_step, imported_data,
separated, stripped, nested,
)
# This is the record data header
parse_record_header(position, nested = nested)
# This is the record data
for i in range(10000000000):
this_line, separated, stripped = get_normal_line()
if this_line == "":
break
parse_normal_record(
position, current_cycle, current_step, imported_data,
separated, stripped, nested,
)
return imported_data
def import_single_file(database_file, debug = False):
"""
checks based on timestamps if any work is required
calls read_neware
then pushes the data to the database
TODO(sam): the demarcation between neware-specific and cycling-general is not clear
Args:
database_file:
debug:
"""
print("IMPORTING FILE {}".format(database_file))
time_of_running_script = timezone.now()
error_message = {}
if (
not database_file.is_valid
or database_file.deprecated
or database_file.valid_metadata is None
):
return error_message
full_path = os.path.join(database_file.root, database_file.filename)
error_message["filepath"] = full_path
already_cached = CyclingFile.objects.filter(
database_file = database_file
).exists()
if not already_cached:
error_message["cached"] = "None"
if already_cached:
f = CyclingFile.objects.get(database_file = database_file)
time_origin = database_file.last_modified
time_cached = f.import_time
if time_origin > time_cached:
already_cached = False
error_message["cached"] = "Stale"
else:
error_message["cached"] = "Valid"
if already_cached:
error_message["error"] = False
return error_message
with transaction.atomic():
f, created = CyclingFile.objects.get_or_create(
database_file = database_file)
def get_last_cycle():
if f.cycle_set.exists():
last_imported_cycle = f.cycle_set.aggregate(Max("cycle_number"))
last_imported_cycle = last_imported_cycle["cycle_number__max"]
else:
last_imported_cycle = -1
return last_imported_cycle
last_imported_cycle = get_last_cycle()
print("\tLAST CYCLE ALREADY IMPORTED: {}".format(last_imported_cycle))
def write_to_database(data_table):
cycles = []
if len(data_table) != 0:
for cyc in list(data_table.keys())[:-1]:
if cyc > last_imported_cycle:
if len(data_table[cyc]) > 0:
passed = False
for step in data_table[cyc].keys():
if len(data_table[cyc][step][1]) > 0:
passed = True
break
if passed:
cycles.append(
Cycle(cycling_file = f, cycle_number = cyc)
)
Cycle.objects.bulk_create(cycles)
steps = []
for cyc in f.cycle_set.filter(
cycle_number__gt = last_imported_cycle
).order_by("cycle_number"):
cyc_steps = data_table[cyc.cycle_number]
for step in cyc_steps.keys():
if len(cyc_steps[step][1]) == 0:
continue
step_type, data = cyc_steps[step]
start_time = min([d[3] for d in data])
second_accuracy = all([d[4] for d in data])
steps.append(
Step(
cycle = cyc,
step_number = step,
step_type = cyc_steps[step][0],
start_time = halifax_timezone.localize(start_time),
second_accuracy = second_accuracy,
)
)
steps[-1].set_v_c_q_t_data(np.array([
d[:3] + [
(d[3] - start_time).total_seconds() / (60. * 60.)
]
for d in data
]))
Step.objects.bulk_create(steps)
f.import_time = time_of_running_script
f.save()
if debug:
data_table = read_neware(
full_path, last_imported_cycle = last_imported_cycle,
)
write_to_database(data_table)
error_message["error"] = False
return error_message
else:
try:
data_table = read_neware(
full_path, last_imported_cycle = last_imported_cycle,
)
except Exception as e:
error_message["error"] = True
error_message["error type"] = "ReadNeware"
error_message["error verbatim"] = e
return error_message
try:
write_to_database(data_table)
error_message["error"] = False
return error_message
except:
error_message["error"] = True
error_message["error type"] = "WriteCache"
return error_message
def bulk_import(cell_ids = None, debug = False):
"""
mostly just calls import_single_file
"""
if cell_ids is not None:
neware_files = get_good_neware_files().filter(
valid_metadata__cell_id__in = cell_ids)
else:
neware_files = get_good_neware_files()
errors = list(map(lambda x: import_single_file(x, debug), neware_files))
return list(filter(lambda x: x["error"], errors))
def is_monotonically_decreasing(qs):
mono = True
for i in range(1, len(qs) - 1):
if qs[i] > qs[i - 1]:
mono = False
break
return mono
def is_monotonically_increasing(qs, mask = None):
mono = True
for i in range(1, len(qs) - 1):
if (
qs[i] < qs[i - 1]
and (mask is None or (mask[i] > .1 and mask[i - 1] > .1))
):
mono = False
break
return mono
def average_data(
data_source_, val_keys, sort_val,
weight_func = None, weight_exp_func = None, compute_std = False,
):
if weight_func is not None:
weights, works = weight_func(data_source_)
else:
weights, works = np.ones(len(data_source_)), np.ones(
len(data_source_), dtype = np.bool,
)
weights = weights[works]
data_source = data_source_[works]
if len(data_source) == 0:
return None
if weight_exp_func is not None:
weights_exp = weight_exp_func(data_source)
else:
weights_exp = np.zeros(len(data_source))
vals = data_source[sort_val]
all_ = np.stack(
[vals, weights, weights_exp] + [data_source[s_v] for s_v in val_keys],
axis = 1,
)
all_ = np.sort(all_, axis = 0)
if len(all_) >= 15:
all_ = all_[2:-2]
elif len(all_) >= 9:
all_ = all_[1:-1]
weights = all_[:, 1]
weights_exp = all_[:, 2]
vals = all_[:, 3:]
max_weights_exp = np.max(weights_exp)
actual_weights = weights * np.exp(
weights_exp - max_weights_exp)
if sum(actual_weights) == 0.0:
actual_weights = None
avg = np.average(vals, weights = actual_weights, axis = 0)
if not compute_std:
return {val_keys[i]: avg[i] for i in range(len(val_keys))}
else:
var = np.average(
np.square(vals - avg), weights = actual_weights, axis = 0,
)
if actual_weights is not None:
actual_weights = (1. / np.sum(
actual_weights) * actual_weights) + 1e-10
actual_weights = np.expand_dims(actual_weights, axis = 1)
var = np.sum(
actual_weights * np.square(vals - avg), axis = 0,
) / (1e-10 + np.abs(
np.sum(actual_weights, axis = 0) - (
np.sum(np.square(actual_weights), axis = 0)
/ (1e-10 + np.sum(actual_weights, axis = 0))
)
))
std = np.sqrt(var)
return {val_keys[i]: (avg[i], std[i]) for i in range(len(val_keys))}
def default_deprecation(cell_id):
"""
TEMPDOC(sam):
this decides which of the duplicate files should be deprecated.
"""
with transaction.atomic():
files = get_good_neware_files().filter(
valid_metadata__cell_id = cell_id)
if files.count() == 0:
return
start_cycles = files.order_by(
"valid_metadata__start_cycle").values_list(
"valid_metadata__start_cycle", flat = True).distinct()
for start_cycle in start_cycles:
files_start = files.filter(
valid_metadata__start_cycle = start_cycle)
if files_start.count() <= 1:
continue
last_modified_max = files_start.aggregate(Max("last_modified"))[
"last_modified__max"]
filesize_max = files_start.aggregate(Max("filesize"))[
"filesize__max"]
# the winners are not deprecated
# the winners are the simultaneously last_modified and largest files
winners = files_start.filter(last_modified = last_modified_max,
filesize = filesize_max)
if winners.count() == 0:
# no winners means no deprecation
continue
winner_id = winners[0].id
files_start.exclude(id = winner_id).update(deprecated = True)
def process_cell_id(cell_id, NUMBER_OF_CYCLES_BEFORE_RATE_ANALYSIS = 10):
# TODO(sam): incorporate resting steps properly.
print("\tPROCESSING CELL ID: {}".format(cell_id))
with transaction.atomic():
fs = get_files_for_cell_id(cell_id)
for f in fs:
steps = Step.objects.filter(cycle__cycling_file = f).order_by(
"cycle__cycle_number", "step_number")
if len(steps) == 0:
continue
first_step = steps[0]
if "Rest" in first_step.step_type:
first_step.end_current = 0.
first_step.end_voltage = 0.
elif "CCCV_" in first_step.step_type:
sign = +1.
if "DChg" in first_step.step_type:
sign = -1.
first_step.end_current_prev = 0.
first_step.constant_current = sign * first_step.maximum_current
first_step.end_current = sign * first_step.minimum_current
if sign > 0:
first_step.end_voltage = first_step.maximum_voltage
first_step.constant_voltage = first_step.maximum_voltage
first_step.end_voltage_prev = first_step.minimum_voltage
else:
first_step.end_voltage = first_step.minimum_voltage
first_step.constant_voltage = first_step.minimum_voltage
first_step.end_voltage_prev = first_step.maximum_voltage
elif "CC_" in first_step.step_type:
sign = +1.
if "DChg" in first_step.step_type:
sign = -1.
first_step.end_current_prev = 0.
first_step.constant_current = sign * first_step.average_current_by_capacity
first_step.end_current = first_step.constant_current
if sign > 0:
first_step.end_voltage = first_step.maximum_voltage
first_step.end_voltage_prev = first_step.minimum_voltage
else:
first_step.end_voltage = first_step.minimum_voltage
first_step.end_voltage_prev = first_step.maximum_voltage
first_step.save()
if len(steps) == 1:
continue
for i in range(1, len(steps)):
step = steps[i]
if "Rest" in step.step_type:
step.end_current = steps[i - 1].end_current
step.end_voltage = steps[i - 1].end_voltage
elif "CCCV_" in step.step_type:
sign = +1.
if "DChg" in step.step_type:
sign = -1.
step.end_current_prev = steps[i - 1].end_current
step.end_voltage_prev = steps[i - 1].end_voltage
step.constant_current = sign * step.maximum_current
step.end_current = sign * step.minimum_current
if sign > 0:
step.end_voltage = step.maximum_voltage
step.constant_voltage = step.maximum_voltage
else:
step.end_voltage = step.minimum_voltage
step.constant_voltage = step.minimum_voltage
elif "CC_" in step.step_type:
sign = +1.
if "DChg" in step.step_type:
sign = -1.
step.end_current_prev = steps[i - 1].end_current
step.end_voltage_prev = steps[i - 1].end_voltage
step.constant_current = sign * step.average_current_by_capacity
step.end_current = step.constant_current
if sign > 0:
step.end_voltage = step.maximum_voltage
else:
step.end_voltage = step.minimum_voltage
step.save()
CycleGroup.objects.filter(cell_id = cell_id).delete()
files = get_good_neware_files().filter(
valid_metadata__cell_id = cell_id)
total_capacity =\
Cycle.objects.filter(cycling_file__database_file__in = files,
valid_cycle = True).aggregate(
Max("dchg_total_capacity"))["dchg_total_capacity__max"]
total_capacity = max(1e-10, total_capacity)
# DISCHARGE
for polarity in [CHARGE, DISCHARGE]:
new_data = []
for cyc in Cycle.objects.filter(
cycling_file__database_file__in = files,
valid_cycle = True).order_by("cycle_number"):
if polarity == DISCHARGE:
step = cyc.get_first_discharge_step()
elif polarity == CHARGE:
step = cyc.get_first_charge_step()
else:
raise Exception("unknown polarity {}".format(polarity))
# if step.end_current_prev is None:
# print(polarity)
# print([s.step_type for s in cyc.step_set.order_by("step_number")])
# print([s.get_v_c_q_t_data() for s in cyc.step_set.order_by("step_number")])
new_data.append(
(
cyc.id, # id
math.log(1e-10 + abs(
step.constant_current) / total_capacity),
# constant current
math.log(
1e-10 + abs(step.end_current) / total_capacity),
# end current
math.log(1e-10 + abs(
step.end_current_prev) / total_capacity),
# end current prev
step.end_voltage,
step.end_voltage_prev,
)
)
if len(new_data) > NUMBER_OF_CYCLES_BEFORE_RATE_ANALYSIS:
new_data = np.array(
new_data, dtype = [
("cycle_id", int),
("constant_rate", "f4"),
("end_rate", "f4"),
("end_rate_prev", "f4"),
("end_voltage", "f4"),
("end_voltage_prev", "f4"),
])
def separate_data(data_table,
splitting_var = "discharge_c_rate"):
rate_step_full = .1 * .5
rate_step_cut = .075 * .5
min_rate_full = np.min(data_table[splitting_var])
min_rate_full = round(
max(min_rate_full, math.log(.005)) - rate_step_full,
ndigits = 1)
max_rate_full = np.max(data_table[splitting_var])
max_rate_full = round(
min(max_rate_full, math.log(500.)) + rate_step_full,
ndigits = 1)
number_of_rate_steps = int(
(max_rate_full - min_rate_full) / rate_step_full) + 2
split_data = {}
prev_rate_mask = np.zeros(len(data_table),
dtype = np.bool)
prev_avg_rate = 0
for i2 in range(number_of_rate_steps):
avg_rate = (rate_step_full * i2) + min_rate_full
min_rate = avg_rate - rate_step_cut
max_rate = avg_rate + rate_step_cut
rate_mask = np.logical_and(
min_rate <= data_table[splitting_var],
data_table[splitting_var] <= max_rate
)
if not np.any(rate_mask):
continue
intersection_mask = np.logical_and(rate_mask,
prev_rate_mask)
if np.array_equal(rate_mask,
prev_rate_mask) or np.array_equal(
intersection_mask,
rate_mask):
prev_rate_mask = rate_mask
prev_avg_rate = avg_rate
continue
elif np.array_equal(intersection_mask,
prev_rate_mask) and np.any(
prev_rate_mask):
if prev_avg_rate in split_data.keys():
del split_data[prev_avg_rate]
split_data[avg_rate] = rate_mask
prev_rate_mask = rate_mask
prev_avg_rate = avg_rate
sorted_keys = list(split_data.keys())
sorted_keys.sort()
avg_sorted_keys = {}
for sk in sorted_keys:
if len(data_table[split_data[sk]][splitting_var]) > 0:
avg_sorted_keys[sk] = np.mean(
data_table[split_data[sk]][splitting_var])
grouped_rates = {}
for sk in sorted_keys:
found = False
for k in grouped_rates.keys():
if abs(avg_sorted_keys[k] - avg_sorted_keys[
sk]) < 0.13:
grouped_rates[k].append(sk)
found = True
break
if not found:
grouped_rates[sk] = [sk]
split_data2 = {}
for k in grouped_rates.keys():
split_data2[k] = np.zeros(len(data_table),
dtype = np.bool)
for kk in grouped_rates[k]:
split_data2[k] = np.logical_or(split_data[kk],
split_data2[k])
return split_data2
summary_data = {}
split_data2 = separate_data(new_data,
splitting_var = "constant_rate")
for k in split_data2.keys():
new_data_2 = new_data[split_data2[k]]
if len(new_data_2) > 0:
split_data3 = separate_data(new_data_2,
splitting_var = "end_rate")
for k2 in split_data3.keys():
new_data_3 = new_data_2[split_data3[k2]]
if len(new_data_3) > 0:
split_data4 = separate_data(new_data_3,
splitting_var = "end_rate_prev")
for k3 in split_data4.keys():
new_data_4 = new_data_3[split_data4[k3]]
if len(new_data_4):
split_data5 = separate_data(new_data_4,
splitting_var = "end_voltage")
for k4 in split_data5.keys():
new_data_5 = new_data_4[
split_data5[k4]]
if len(new_data_5) > 0:
split_data6 = separate_data(
new_data_5,
splitting_var = "end_voltage_prev")
for k5 in split_data6.keys():
new_data_6 = new_data_5[
split_data6[k5]]
if len(new_data_6) > 0:
avg_constant_rate = np.mean(
new_data_6[
"constant_rate"])
avg_end_rate = np.mean(
new_data_6[
"end_rate"])
avg_end_rate_prev = np.mean(
new_data_6[
"end_rate_prev"])
avg_end_voltage = np.mean(
new_data_6[
"end_voltage"])
avg_end_voltage_prev = np.mean(
new_data_6[
"end_voltage_prev"])
summary_data[(
avg_constant_rate,
avg_end_rate,
avg_end_rate_prev,
avg_end_voltage,
avg_end_voltage_prev)] = new_data_6
for k in summary_data.keys():
cyc_group = CycleGroup(cell_id = cell_id,
constant_rate = math.exp(k[0]),
end_rate = math.exp(k[1]),
end_rate_prev = math.exp(k[2]),
end_voltage = k[3],
end_voltage_prev = k[4],
polarity = polarity
)
cyc_group.save()
if polarity == CHARGE:
Cycle.objects.filter(
id__in = list(summary_data[k]["cycle_id"])).update(
charge_group = cyc_group)
elif polarity == DISCHARGE:
Cycle.objects.filter(
id__in = list(summary_data[k]["cycle_id"])).update(
discharge_group = cyc_group)
def process_single_file(f, DEBUG = False):
error_message = {"filename": f.database_file.filename}
print("\tPROCESSING SINGLE FILE: {}".format(f.database_file.filename))
def thing_to_try():
with transaction.atomic():
if f.process_time <= f.import_time:
# must process the step data to summarize i
for cyc in f.cycle_set.filter(processed = False):